A note for readers who do not read Chinese: Chinese is written without spaces between words, and in CSS a line may break between any two characters. A typical word is two or three characters long, so a browser can easily break a word in the middle. This post is about stopping that. The examples below are shown in pinyin (one syllable per character), so you can see where the breaks fall.
Looking at the blog list on my phone, a heading was breaking like this (translation of the heading: "Gray text plus another layer of opacity: the first accessibility scan found 20 problems"):
The word "accessibility" (wu-zhang-ai, three characters) was cut in two, and the first line left a third of its width empty on the right.
Cause: balance does not understand Chinese words
Every heading on the site has text-wrap: balance, which makes the browser lay out two lines at similar lengths, and it looks great for English headings. But in CSS Chinese can break between every two characters, and to even the lines out, balance picked a spot in the middle of a word.
My first thought was word-break: auto-phrase, which breaks by word. But it currently only supports Japanese (lang="ja") and does nothing for Traditional Chinese.
The approach: segment on the server, insert <wbr>
JavaScript has a built-in Intl.Segmenter, backed by ICU's Chinese dictionary:
For a heading meaning "Flight poster generator: the route from Tokyo to Los Angeles", it returns one piece per word, which in pinyin looks like this:
I insert <wbr> between words and set word-break: keep-all on the outside (so the browser no longer breaks between Han characters on its own). The only places a line can break are then <wbr>, spaces and punctuation. Balance still works, but now picks from those positions:
It is written as a Server Component, <Phrase>, and you just wrap the heading in it. The segmentation happens on the server, so the browser receives HTML with the <wbr> already in place and downloads no extra JavaScript.
Three details
- The dictionary is not perfect: "accessibility" (wu-zhang-ai) gets split into wu | zhang-ai, and "robot" (ji-qi-ren) into ji-qi | ren. The file holds a
KEEPlist of words that never get a<wbr>inside, with a unit test - Never before punctuation: otherwise a line could start with a full-width colon. Nothing is inserted after an opening quotation bracket either
- Server only: the client's ICU version may segment differently from Node's, and hydration would mismatch. The component has
import "server-only", so misuse fails the build
Result
The blog list, article page headings and the latest-posts cards on the home page all use it. Comparing 390px-wide phone screenshots, headings that used to break in the middle of words ("accessibility" as wu / zhang-ai, "semantic search" as yu / yi-sou-xun, "site AI" as wang / zhan AI) now break between words.