CSS balanced text
05.05.2025When centered or justified alignment is not enough.
This is a leftover technique from my failed project milo.sc. I was looking for a way to center a line of text - not absolutely to the width of a container, but around a specific symbol of icon. For example:
Anna ♥ Matt
Looks pretty symmetric! I could do text-align: center;
and call it a day. Unfortunately, people have names of different lengths like:
Constantine ♥ Mia
The heart is now pushed to the right, but my design required it to stay in the center. The ideal solution should be:
- pure CSS;
- accessible (readable by screen readers and, as a bonus, possible to select the text - so no
content
property or images/icons).
Implementation consists of flex container with three children, the outermost ones set to grow equally. The middle one stays centered and only as wide as its content. Now we only need to “glue” the left side label to the rest, by setting text-align: right;
on it. Spaces between words can be inlined or added with ::before
/::after
pseudoelements.
See the demo below. Although it’s a very minor invention, writing about it let me recall the fun days of hobby coding, and reinforce my will to be ever enjoying CSS. Too often it’s overlooked in favor of different components and eventually authored only to brute-force some behavior.