CSS balanced text

05.05.2025

When 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:

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.

See the pen on CodePen.