Truncate text with an ellipsis in CSS
3 Truncate one line with an ellipsis
easyCut a single line of text that is too long for its container and finish it with an ellipsis.
Stuck? Three hints, smallest first
- 1. Three properties are all required together:
white-space: nowrap,overflow: hidden,text-overflow: ellipsis. - 2. Leave out
nowrapand the text wraps instead of truncating, so the ellipsis never appears. - 3. The element also needs a width limit, or there is nothing to overflow.
<p class="one-line">
This sentence is deliberately far too long to fit on a single line inside its box.
</p>
.one-line {
max-width: 240px;
white-space: nowrap; /* without this it wraps and never truncates */
overflow: hidden; /* without this it spills out visibly */
text-overflow: ellipsis; /* without this it is simply cut off */
border: 1px solid #d7d8dc;
padding: 8px;
border-radius: 6px;
}
6 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('the text cannot wrap', declares(css, 'white-space', 'nowrap'), true);
test('the overflow is hidden', declares(css, 'overflow', 'hidden'), true);
test('the ellipsis is asked for', declares(css, 'text-overflow', 'ellipsis'), true);
test('there is a width to overflow', declares(css, 'max-width', '240px'), true);
test('all three properties are present, not just one', ['white-space', 'overflow', 'text-overflow'].every((p) => new RegExp(p + '\\s*:').test(css)), true);
test('one paragraph', countTag(html, 'p'), 1);
Output
All three properties are load-bearing and the failure modes are different: without nowrap the text wraps and you never see an ellipsis; without overflow: hidden it spills past the border; without text-overflow it is chopped mid-letter. That is why the fifth assertion checks for all three rather than any one. Worth knowing this only works for a single line — multi-line clamping needs -webkit-line-clamp.