December 18th, 2023
Have you ever found yourself playing a guessing game with line breaks, wondering if your text will elegantly wrap itself around the page? As a developer, I've been there, and I can confirm – it's a real struggle. Achieving a balanced text wrap becomes quite a challenge when you lack information about the size, font, or even the language of a headline.
To overcome this issue, CSS recently introduced
text-wrap: balance
. This new property brings
the art of balancing text in an automated way, with just one line of
code.
Let's take a closer look. Click on the headline below to experience the magic!
As we can see, the style ensures that the text is distributed evenly across multiple lines, enhancing layout quality and readability.
To achieve balancing, all we need to do is simply add
text-wrap: balance
to the element we want to
style. As shown in the code below, both paragraphs are constrained to a
max-inline-size
of 60ch. However, we note the
difference between the two text blocks. The first one, lacking the style
has a hanging orphan (single word at the end). While the second one,
with the applied style, rearranges for a cleaner and more cohesive
display.
While text-wrap: balance
provides a great
solution for wrapping text, it has some performance constraints. It can
only be applied to 4 or less lines of text. As a result, it should
primarily be used for headlines. Consider adding the following snippet
of code to your next project.
It's important to note that applying the property will not change the inline-size or max-width of the element.
As we can see in the illustration, applying
text-wrap: balance
modifies the arrangement of
the words rather than the max-width. In some cases, this can lead to
notable white space which may result in a poor design.
The text-wrap: balance
property does not
support all browsers. It is currently compatible with
Google Chrome, Microsoft Edge, and Mozilla Firefox. It has experimental support on Safari Technology Preview as well,
which gives you an early look at upcoming web technologies on Apple
platforms.
Overall, incorporating
text-wrap: balance
into your web development
toolkit proves to be a game-changer for achieving balanced and visually
appealing text layouts. The struggle of guessing line breaks becomes a
thing of the past as this innovative CSS property automates the art of
balancing text with just one line of code.