Truncate Text Without Breaking the Layout
One line, several lines, and the flexbox trap that makes ellipsis silently stop working.
Loading…
One line, several lines, and the flexbox trap that makes ellipsis silently stop working.
Loading…
.title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
All three are required. text-overflow does nothing without overflow: hidden, and without white-space: nowrap the text just wraps instead of
overflowing.
.excerpt {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}
The -webkit- prefixes look alarming but are supported everywhere, including
Firefox. Note it needs display: -webkit-box, which means the element stops
being a block — margins on children behave differently, so clamp the
paragraph itself rather than its wrapper.
Where supported, the unprefixed shorthand is now the same thing in one line:
.excerpt { line-clamp: 3; }
A flex or grid item's min-width defaults to auto, which means "at least
as wide as my content". A long unbroken title therefore refuses to shrink,
overflows its container, and the ellipsis never appears — the box is always
big enough for the text.
.row { display: flex; gap: 1rem; }
.row > .title {
min-width: 0; /* the fix — let it shrink below its content */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
In a grid, the same fix is min-width: 0 on the item, or defining the track
as minmax(0, 1fr) instead of 1fr. This single line is behind a large share
of "my ellipsis doesn't work" bugs.
Ellipsis is for text you are deliberately cutting. For URLs, hashes and IDs that must stay visible, break them instead:
.hash {
overflow-wrap: anywhere; /* break only when it would otherwise overflow */
word-break: break-word; /* older engines */
}
Avoid word-break: break-all on prose — it breaks every line at the exact
edge, mid-word, and reads badly.
A truncated string is still truncated for screen readers only if it is visually clipped — the full text stays in the accessibility tree, which is what you want. What you should add is a way for sighted users to get it back:
<span class="title" title="The full untruncated heading">The full untruncated heading</span>
Don't put different text in title than in the element — that reads as two
conflicting labels to assistive tech.