CSS fix to prevent orphan icons dropping to a new line
When an HTML element becomes too narrow, its content starts to wrap into multiple lines. This is intended behavior and works well in many cases. However, for short text, it doesn't look great when the last word or icon drops to the next line, becoming an orphan.
For example, you might see something like this:
It doesn't look great when the icon is left alone on its own row. Luckily, there's a simple CSS solution.
Solution
Only thing we need to add is a single line of CSS:
This property tells the browser to wrap the text in a way that best balances the number of characters on each line, enhancing layout quality and legibility. The browser will calculate this for us, preventing orphaned icons or words.
text-wrap: pretty
There is also the pretty value for text-wrap, which is even better. It works in a similar way, but the browser will use a slower algorithm that prioritizes better layout over speed.
Unfortunately, at the time of writing, pretty
is not supported in Firefox nor Safari. However, you can define both values, and browsers that don't support pretty
will fall back to balance
.
/* This will be ignored by browsers that don't support it. */
Demo
Here's a simple demo. Use the handle on the right to resize the element and see how text breaks with and without the balance
property applied.
text-wrap: pretty
.