Steering browser line breaks with invisible characters
Good typography is difficult to achieve on the web. Compared to typesetting
engines like LaTeX or Typst, 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 and produces eerie narrower
paragraphs with Safari. Various good
implementations of the Knuth-Plass algorithm 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.
Comparison with existing solutions
Let's benchmark with a short paragraph in French from Jules Verne's "L'�le mystérieuse":
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 images below show the rendered layout for the three main web engines. Visit the live page 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 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. 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), except near the end of the paragraph, and to insert non-breaking spaces (U+00A0) 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, while the
specification for text-wrap: pretty leaves the algorithm to each
browser.
Implementation
My custom static site generator includes a step to alter HTML files: add a table of contents, turn footnotes to sidenotes, add links for the print version, include the script and CSS files required to render the page, 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:
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 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, a compiler to turn Python code into C extensions.
I converted the regular expressions to hand-written loops, stole the Liang hyphenation algorithm from Pyphen, and moved them to Cython using the pure Python syntax 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.
Is it worth it?
As with vertical rhythm, 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 reviewed a first draft of this article. Any errors are still mine!
-
For each browser engine, paragraph width, and feature, a test harness recorded the position of each letter. Some JavaScript code replays the rendered layout. ↩
-
Various sources incorrectly refer to runts as widows or orphans. In The Elements of Typographic Style, Robert Bringhurst explains the difference between widows and orphans, which are less of a concern on the web without the concept of pages:
Isolated lines created when paragraphs begin on the last line of a page are known as orphans. They have no past, but they do have a future, and they need not trouble the typographer. The stub-ends left when paragraphs end on the first line of a page are called widows. They have a past but no future, and they look foreshortened and forlorn.
-
Robert Bringhurst dictates four as the minimum word length alone on the last line, but many prefer more than that.
2.4.2. Avoid leaving the stub-end of a hyphenated word, or any word shorter than four letters as the last line of a paragraph.
-
It should match the behavior of a recent Safari 26, except maybe on the hyphenation dictionary. ↩
-
To show these marks on any page of this blog, type � � s. ↩
-
The example only shows same-length substitutions. To handle the general case, we must also refresh the positions. ↩
-
The Python JIT could have given good results. As it is likely to be removed, I didn't try. ↩
26 November, 2026 01:19PM by Vincent Bernat




















out' position" alt="The whole CR box assembled, with the fan in the 'in -> out' position">









