The many ways to deal with overflowing text
For a visual reference, this is usually what happens if you don't handle long words.
We certainly did not intend for that to happen, so here are 7 different strategies to wrap your text.
Break only if text overflows
Most of the time, you just want your long words to wrap, the css declaration overflow-wrap: break-word
will do the job.
Break only if text overflows, and minimize width
Compared to the previous declaration, overflow-wrap: anywhere
will wrap at word boundaries when possible to reduce the min-content width.
To better illustrate the differences, here are two static boxes with their width set to width: min-content
. The first box is overflow-wrap: anywhere
, and the second overflow-wrap: break-word
.
As such, overflow-wrap: anywhere
is usually only applied individually on long words, and not on a paragraph.
Break anywhere
If you don't care about preserving word boundaries, and you just want your text to wrap, then look no further than using the css declaration word-break: break-all
. This trades off readability for more compact text.
Force break at certain places with hyphens
Using ‐
, the hard hyphen character entity, we can manually break up long words with hyphens (-) and use the default breaking algorithm without any css.
This is what the html looks like:
The longest word in the english dictionary is
"Pneumono‐ultra‐microscopic‐silico‐volcano‐coniosis"
Break at certain places with hyphens
Alternatively, using ­
, also known as the soft hyphen character entity, hyphens will only appear when a word break occurs.
This is what the html looks like:
The longest word in the english dictionary is
"Pneumono­ultra­microscopic­silico­volcano­coniosis"
Break at certain places without hyphens
If you want to break up long words without hyphens, then the <wbr>
html element is what you're looking for.
This is what the html looks like:
The longest word in the english dictionary is "Pneumono<wbr />ultra<wbr />microscopic<wbr />silico<wbr />volcano<wbr />coniosis"
Automatically break with hyphens
By using the css declaration hyphens: auto
and an html lang
attribute, we can let the browser decide when to insert a hyphen.
The browser will also prioritize ‐
and ­
if they are present.
The longest word in the english dictionary is "Pneumonoultramicroscopicsilicovolcanoconiosis"
This is what the html looks like:
<p lang="en">
The longest word in the english dict­ionary is
"Pneumonoultramicroscopic­silicovolcanoconiosis"
</p>
As we can see, this method is limited by the browser's hyphenation rules. Its support also varies depending on the language and browser. Please use this method with care.