Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readCSS

Improve paragraph breaks with text-wrap: pretty

Use text-wrap: pretty to improve paragraph line breaks without adding manual breaks or nonbreaking spaces.

Your paragraph fits in three lines, with door. sitting by itself on the third. You could join the last two words with a nonbreaking space, then watch the awkward break move when someone changes the copy or opens the page on a narrower screen. Give the browser permission to choose better breaks with text-wrap: pretty.

Let the last few lines trade words

Use the sentence “Leave the spare key under the blue flower pot by the back door.” For the comparison, create two paragraphs with that text. Give the second the class pretty.

p {
  width: 217px;
  font: 16px Arial, sans-serif;
}

p.pretty {
  text-wrap: pretty;
}

With Chromium using Arial at this width, the first paragraph ends with door. on its own line. The second ends with back door.. Both occupy three lines.

diagram

One paragraph at the same width

At the same width, pretty moves words between lines and gives the last word a neighbor.

Compare the first two lines as well. The default breaks after the and back. With pretty, the first line ends at under, which leaves room to shift words down through the paragraph. Your copy stays a single text node that can reflow at another width.

Apply it to reading text

In your own layout, put text-wrap: pretty on the article paragraphs and keep the widths you already use. The fixed width above exists to make the breaks reproducible. Select the paragraph elements when the surrounding article also contains code blocks or headings with their own wrapping rules.

pretty asks the browser to spend more effort on line breaks. Exact breaks depend on the engine, font and available width. Compare Chromium's wrapping example with WebKit's implementation notes if you see different results in two browsers.

For a two-line heading, text-wrap: balance aims for lines of similar length. For the paragraphs below it, pretty asks the browser to improve line breaks for reading text.

Check a few real paragraphs at the narrow end of your layout. Look after the web font loads, and include a long name or link. If one token is wider than the column, set a break rule such as overflow-wrap: anywhere for that content. Choosing a prettier line break still requires places where the browser can break.