HomeGuideLabGlossary

Truncate text when flex item shrinks

The Solution at a Glance

Truncating text can be useful sometimes

Imagine you have a flex container with a bunch of flex items that are likely to shrink in size. If you have text inside a flex item, that text will normally wrap into multiple lines of text as needed to adapt to the shrinking size of the flex item.

But as the flex item shrinks in one direction, this wrapping of the text can make the flex item bigger in the other direction. This may not be what you want, especially if you have some fixed size constraints.

Kiwisare greenYou may not want the flex item to expand this way

Instead, you’d like all of the text inside the flex item to be on a single line of text. And as the flex item shrinks and the text can’t fit anymore, that text should be truncated with an ellipsis instead of wrapping.

Kiwis...

Prevent the text inside the flex item from wrapping with white-space: nowrap

Prevent the line breaks with white-space: nowrap. This will force all the text inside the flex item to be laid out in a single line.

Kiwis are green

Normally, flex items automatically calculate a minimum size below which they won’t shrink. When text is allowed to wrap, this minimum size is equal to the size of the longest word that can’t be broken into multiple lines of text.

But because now we said that none of the text can be broken, this will now be the automatic minimum size of the flex item.

Kiwis are greenmin-inline-size: auto

Obviously we want to shrink past that and truncate the text. We could set something like min-inline-size: 0, which will overwrite the initial min-inline-size: auto. This will let us shrink the flex item, but the text will overflow it.

Kiwis are greenmin-inline-size: 0

Hide the overflowing text with overflow: hidden

We can hide any text that would overflow the flex item as it shrinks with overflow: hidden. This is closer to what we want.

And, by the way, the moment we set overflow to something else than the initial visible, the automatic minimum size switched from being content-based to zero! We can now remove the min-inline-size: 0 declaration.

Kiwis are greenoverflow: hidden

Place an ellipsis at the end of overflowing text with text-overflow: ellipsis

Finally, set text-overflow to ellipsis to show an ellipsis at the end of the truncated text.

Ki...s are greentext-overflow: ellipsis