Steering browser line breaks with invisible characters
Vincent Bernat
Good typography is difficult to achieve on the web. Compared to typesetting
engines like LaTeX[1] or Typst[2], the web still lacks a good line-breaking
algorithm. The CSS directive text-wrap: pretty tries to improve the situation
but is still not implemented in Firefox[3] and produces eerie narrower
paragraphs with Safari[4]. Various[5] good[6]
implementations[7] of the Knuth-Plass algorithm[8] exist in
JavaScript, but they either reflow the text or delay its display. Instead, I
taught my static site generator to manually insert soft hyphens and
non-breaking spaces at tactical locations to achieve a predictable, okayish result.
🎟️ Special time-limited offer
The articles on this blog are flushed left and ragged right, but for this one, you can change how the paragraphs are set:
- ;
- , , or ;
- (as your browser does not support it, it shouldn’t change anything).
Comparison with existing solutions#
Let’s benchmark with a short paragraph in French from Jules Verne’s “L’Île mystérieuse[9]”:
Le marin pressa la main du reporter, dont il ne pouvait se faire entendre, et d’une façon qui signifiait : « Attendez ! » puis, il rentra dans le couloir. Un instant après, il ressortait avec un fagot allumé, il le projetait dans les ténèbres, et il poussait des sifflements aigus.
The animations below show the rendered layout for the three main web engines.1 Hover the animations and they will pause. Move the mouse near the vertical red bars to adjust the paragraph widths. Enable or disable CSS directives with the checkboxes below.
The images below show the rendered layout for the three main web engines. You need JavaScript to animate the paragraph widths and compare the effects of the various features.
Let’s try Firefox 160 first. The most notable “defect” for this paragraph is the word “aigus”: it may stay alone on the last line—or even be hyphenated. This is a “runt.”2 With hyphenation disabled, runts are rarer, but the layout introduces “bad rags”: a large blank space between the end of a line and the right margin, like in the second line when the paragraph width is 825 pixels. When the paragraph is justified, bad rags are translated into larger spaces between words. These traits make your text look poor and should be avoided.3
Unlike Firefox, Chromium 157 implements text-wrap: pretty. It adjusts
paragraphs ending with a word alone on the last line[11] by
adjusting the break points for the last four lines to hold two last words
together, like “sifflements aigus” in our example.
Like Firefox, WebKitGTK 2.544 may hyphenate “aigus,” leaving
a very short runt on the last line. With text-wrap: pretty and without
justification, it often creates shorter paragraphs[12]. When enabling both
pretty wrapping and justification, WebKitGTK performs worse than any other
browser in this example as it inserts too much space.
My solution is to insert soft hyphens (U+00AD[13]), except near the end of the paragraph, and to insert non-breaking spaces (U+00A0[14]) to meet the minimal requirement to prevent a runt. In my case, I set the limit to 8 characters, punctuation included.
The animation below marks each non-breaking space with a purple triangle and
every soft hyphen with a vertical red line.5 With hyphens: manual, the
browser may insert a line break anywhere a soft hyphen is present.
Such an approach cannot match a proper line-breaking algorithm, but it works in
Firefox, prevents the shortened paragraphs in Safari, and sometimes provides
better results than what Chromium did, as it allows hyphenation of
“sif‐fle‐ments.” Moreover, all browsers will break lines at the same
places: with hyphens: auto, each browser uses its own hyphenation dictionary
and Safari ignores hyphenate-limit-chars[15], while the
specification for text-wrap: pretty[16] leaves the algorithm to each
browser.
Implementation#
My custom static site generator[17] includes a step to alter HTML files: add a table of contents[18], turn footnotes to sidenotes[19], add links for the print version[20], include the script and CSS files required to render the page[21], etc. This looks like a good place to fix the HTML code to hyphenate words and insert non-breaking spaces.
I also add a bit of typographic sugar: I convert the straight single quotes
'…' and double quotes "…" to their curly equivalents: ‘…’ and “…”; I
turn an ellipsis ... into its dedicated equivalent …; I add a narrow
non-breaking space before a double punctuation or between two groups of digits
in French, like in “Ça fait donc 501 622 731.”
We could implement these transformations with regular expressions and a hyphenation library like Pyphen[22]:
NNBSP = "\u202f" # NARROW NO-BREAK SPACE
SHY = "\u00ad" # SOFT HYPHEN
NBSP = "\u00a0" # NO-BREAK SPACE
opening_quote = re.compile(r"""(?<![^\s(\[{])(['"])(?!\s)""")
closing_quote = re.compile(r"""(?<=[^\s(\[{])(['"])""")
space_before_punct = re.compile(r"\s([:;!?%»])")
space_after_punct = re.compile(r"«\s")
last_chars = re.compile(r"(?:[^\s\xad][\s\xad]*){1,8}$")
word = re.compile(r"\w+")
def typography(text: str, lang: str) -> str:
r"""Apply typographic rules to text.
>>> typography('"Don\'t panic," he said.', "en_US")
'“Don’t panic,”\xa0he\xa0said.'
>>> typography("« Attendez ! »", "fr")
'«\u202fAt\xadtendez\u202f!\u202f»'
"""
text = opening_quote.sub(lambda m: "‘" if m[1] == "'" else "“", text)
text = closing_quote.sub(lambda m: "’" if m[1] == "'" else "”", text)
text = space_before_punct.sub(NNBSP + r"\1", text)
text = space_after_punct.sub("«" + NNBSP, text)
text = text.replace("...", "…")
# Hyphenation
hyphenator = pyphen.Pyphen(lang=lang, left=2, right=3)
text = word.sub(lambda m: hyphenator.inserted(m[0], SHY), text)
# No line break in the last 8 characters
text = last_chars.sub(
lambda m: m[0].replace(SHY, "").replace(" ", NBSP), text
)
return text
However, it breaks if we have HTML tags in the middle:
<p>I have read "<a href="https://en.wikipedia.org/wiki/Dune_(novel)">Dune</a>".</p>
The naive regular expression transforms the quotes of the href attribute. If
we apply the regular expression to each text node, we get I have read “Dune“.
Dealing with HTML#
While we could tune the regular expressions, this approach is quite fragile. We
need to apply the transformations to the plain text and stitch the HTML markup
back into the result. I use the lxml library[23] to parse and manipulate
HTML. Iterating over each block and extracting the text is straightforward, but we
lose all the inner markup:
for block in root.iter("p", "li", "h1", "h2", "h3"):
text = typography("".join(block.itertext()), "en_US")
Instead, we need to keep track of the position of each group of letters in a depth-first walk of the HTML tree. For example, we split the text from the previous HTML specimen into three slots:
slots = [
["p.text", 0, 'I have read "'],
["a.text", 13, "Dune"],
["a.tail", 17, '".'],
]
text = "".join(slot[2] for slot in slots)
We translate modifications to the text into a list of substitutions: start position, end position, and new text.
changes = []
for m in opening_quote.finditer(text):
start, end = m.span(1)
changes.append((start, end, "‘" if m[1] == "'" else "“"))
for m in closing_quote.finditer(text):
start, end = m.span(1)
changes.append((start, end, "’" if m[1] == "'" else "”"))
# changes = [(12, 13, "“"), (17, 18, "”")]
To apply a substitution, we locate the slot it applies to and update the text.6
for start, end, new in changes:
slot = next(slot for slot in reversed(slots) if slot[1] <= start)
offset = start - slot[1]
slot[2] = slot[2][:offset] + new + slot[2][offset + end - start :]
# slots = [["p.text", 0, "I have read “"],
# ["a.text", 13, "Dune"],
# ["a.tail", 17, "”."]]
We can stitch the modifications back into the HTML tree with a second depth-first walk, amending the text nodes when they are different from what we recorded in the slots.
Faster with Cython#
For this task, Python is not the fastest language on this side of the galaxy.7 But we can significantly speed up some parts of the code with Cython[24], a compiler to turn Python code into C extensions.
I converted the regular expressions to hand-written loops, stole the Liang hyphenation algorithm[26] from Pyphen, and moved them to Cython[27] using the pure Python syntax[28] along with the code keeping track of the HTML structure. As a result, the code is four times faster! 🚀
Inline code#
I handle inline code a bit differently: I insert zero-width spaces before some
markers: ., _, /, =, and :. This lets the browser split a long IPv6
address, like 2a01:e0e:c03c:f44e:dabc:7337:38fa:ff40, or a Python method name,
like xxhash.xxh3_128_hexdigest(), at those markers. As far as I know, this is
not something possible with just CSS.
Copy/paste#
When copying text, some browsers may keep the soft hyphens or zero-width spaces.
This is annoying when pasting into a terminal. We can intercept the “copy” event
and strip these special characters from the text/plain version recorded in the
clipboard:
document.addEventListener("copy", (event) => {
const selection = document.getSelection();
const raw = selection.toString();
const text = raw
// SOFT HYPHEN, ZERO WIDTH SPACE
.replace(/[\u00ad\u200b]/g, "")
// NO-BREAK SPACE, NARROW NO-BREAK SPACE
.replace(/[\u00a0\u202f]/g, " ");
if (text === raw) return;
const div = document.createElement("div");
for (let i = 0; i < selection.rangeCount; i++)
div.appendChild(selection.getRangeAt(i).cloneContents());
event.clipboardData.setData("text/plain", text);
event.clipboardData.setData("text/html", div.innerHTML);
event.preventDefault();
});
Soft hyphens don’t interfere with other features, like browsers’ find-in-page or indexing by Pagefind[29].
Is it worth it?#
As with vertical rhythm[30], no one would notice this small arrangement if it weren’t for this article. But, you know what? I notice it, and it makes me happy. So I’ll keep spending time on pointless stuff like this because it soothes me. 🍃

Note
Maytham Alsudany[31] reviewed a first draft of this article. Any errors are still mine!
- https://www.latex-project.org/
- https://typst.app/
- https://bugzilla.mozilla.org/show_bug.cgi?id=1960910
- https://mjtsai.com/blog/2025/04/11/css-text-wrap-pretty-in-webkit/
- https://github.com/robertknight/tex-linebreak
- https://justif.lyall.co/
- https://github.com/egilll/tex-linebreak2
- https://gwern.net/doc/design/typography/tex/1981-knuth.pdf
- https://www.gutenberg.org/ebooks/14287
- https://en.wikipedia.org/wiki/The_Elements_of_Typographic_Style
- https://chromestatus.com/feature/5145771917180928
- https://matklad.github.io/2026/02/14/justifying-text-wrap-pretty.html
- https://www.compart.com/en/unicode/U+00AD
- https://www.compart.com/en/unicode/U+00A0
- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/hyphenate-limit-chars
- https://drafts.csswg.org/css-text-4/#text-wrap-style
- https://github.com/vincentbernat/vincent.bernat.ch/blob/d2f41d4cd55080db009fbf1cab6ab8b5f5f1af52/ssg
- https://github.com/vincentbernat/vincent.bernat.ch/blob/d2f41d4cd55080db009fbf1cab6ab8b5f5f1af52/ssg/html/toc.py
- https://github.com/vincentbernat/vincent.bernat.ch/blob/d2f41d4cd55080db009fbf1cab6ab8b5f5f1af52/ssg/html/sidenotes.py
- https://github.com/vincentbernat/vincent.bernat.ch/blob/d2f41d4cd55080db009fbf1cab6ab8b5f5f1af52/ssg/html/print.py
- https://github.com/vincentbernat/vincent.bernat.ch/blob/d2f41d4cd55080db009fbf1cab6ab8b5f5f1af52/ssg/html/asset.py
- https://pyphen.org/
- https://lxml.de
- https://cython.org/
- https://lwn.net/Articles/1102102/
- https://www.tug.org/docs/liang/liang-thesis.pdf
- https://github.com/vincentbernat/vincent.bernat.ch/blob/d2f41d4cd55080db009fbf1cab6ab8b5f5f1af52/ssg/html/ctypography.py
- https://docs.cython.org/en/latest/src/tutorial/pure.html
- https://pagefind.app/
- https://vincent.bernat.ch/en/blog/2026-css-vertical-rhythm
- https://maytham.aezign.au/