Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to truncate text with an ellipsis

Short answer

Three properties are needed together: no wrapping, hidden overflow and an ellipsis:

<p style="width: 220px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">A very long product name that does not fit on one line</p>

white-space: nowrap keeps the text on one line, overflow: hidden hides what does not fit, and text-overflow: ellipsis puts an ellipsis where the text is cut.

Several lines

line-clamp keeps a given number of lines. For now the property works with a prefix and together with display: -webkit-box:

<p style="width: 220px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;">A long product description that takes more than two lines, so the rest of the text hides behind an ellipsis.</p>

Despite the prefix, this syntax works in every modern browser.

Truncating inside a flex row

Inside flexbox text does not shrink below its own width by default. Add min-width: 0 to the text item:

<div style="display: flex; gap: 8px; width: 240px;">
  <span style="min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">anna.smith.long.email@example.com</span>
  <button>Edit</button>
</div>

Common mistake

The ellipsis does not appear if the element has no limited width or is inline, like a span outside flexbox. text-overflow only works on a block with a width and overflow: hidden — on their own these properties do not cut anything.

Functions used in this recipe

  • text-overflow — How text that does not fit is cut: abruptly or with an ellipsis.
  • white-space — How spaces and line breaks in the source are handled and whether lines may wrap.
  • overflow — What to do with content that does not fit into the element.

Thanks for reading!

Donate to the site — we work hard for you.