text-wrap

Evens out line lengths in headings and the like, or keeps a single word from being left alone on the last line of body text. Replaces the line breaks you used to put into headings by hand with a CSS declaration.

Modern approach

The browser evens out the line lengths, so you don’t need <br>. Keep the same <span> around groups of words you want to stay together. balance evens out the lines using only the breaks between them.

h2 {
  text-wrap: balance;
}

.nowrap {
  white-space: nowrap;
}
<h2>
  <span class="nowrap">With new features,</span>
  <span class="nowrap">replace the</span>
  <span class="nowrap">old technique</span>
</h2>

Legacy approach

To keep the last line from ending up short, a <br> was put into the heading and hidden on narrow screens. Groups of words were sometimes wrapped in a <span> with white-space: nowrap so they wouldn’t break apart. Every time the wording or the viewport width changed, the break position had to be decided again.

.nowrap {
  white-space: nowrap;
}

@media (max-width: 767px) {
  .hidden-md {
    display: none;
  }
}
<h2>
  <span class="nowrap">With new features,</span><br class="hidden-md" />
  <span class="nowrap">replace the</span>
  <span class="nowrap">old technique</span>
</h2>

Things to watch when replacing

  • With balance alone, Japanese text can break in the middle of a word. word-break: auto-phrase, which breaks at phrase boundaries, still works only in Chrome, so keep the parts you don’t want broken wrapped in <span>.
  • balance has worked in all browsers only since May 2024, when Safari 17.5 added it. That’s later than text-wrap became available everywhere (March 2024).
  • pretty, meant for body text, isn’t supported in Firefox yet.
  • balance only applies to short text: up to 6 lines in Chromium and up to 10 lines in Firefox. For longer headings, it doesn’t change how lines wrap.
  • Remove the old <br> before replacing it. If you leave it in, the line always breaks there.

Fallback

Browsers without support just wrap normally, and the heading stays readable. white-space: nowrap on the <span> works in those browsers too, so words still don’t break in the middle. All five target browsers support it, so you normally don’t need to add anything.

Browser Support

  • Chrome

    v114+
    2023-05-30
  • Edge

    v114+
    2023-06-02
  • Safari

    v17.4+
    2024-03-05
  • Safari (iOS)

    v17.4+
    2024-03-05
  • Firefox

    v121+
    2023-12-19

Search by feature name or code

e.g. aspect-ratio, :has(), padding-top

Try a different word or a property name.

Could not load search.