Multi-line Text Truncation
Single-line truncation is solved with `text-overflow: ellipsis`, but truncating to N lines requires the WebKit line-clamp API. This snippet covers the standard three-line ellipsis using the modern `line-clamp` shorthand, the older `-webkit-line-clamp` form for broader support, and a JS-free fade-out variant for browsers without line-clamp.
586 views
13
.clamp-3 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
line-clamp: 3;
overflow: hidden;
}Five lines of CSS, but every one matters. display: -webkit-box plus -webkit-box-orient: vertical opt the box into the WebKit line-clamp model, -webkit-line-clamp sets the line count, and overflow: hidden clips the rest with an ellipsis. The unprefixed line-clamp is now in the standard track and works without the prefixes on modern browsers, but the prefixed properties are still needed for older Safari and Edge. The container needs a finite width or the truncation never engages.
.clamp {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: var(--lines, 2);
line-clamp: var(--lines, 2);
overflow: hidden;
}
.title {
--lines: 1;
}
.summary {
--lines: 4;
}Hard-coding the line count per use case bloats the stylesheet. A CSS custom property lets every consumer override only the line count while sharing the rest of the rule. Falling back to 2 inside var(--lines, 2) gives a sensible default when a wrapper forgets to set it. This pattern is what design systems use to expose a clamp utility class with a single --lines knob, which keeps the surface area tiny.
.fade-clamp {
position: relative;
max-height: 4.5em;
overflow: hidden;
line-height: 1.5;
}
.fade-clamp::after {
content: "";
position: absolute;
inset: auto 0 0 0;
height: 1.5em;
background: linear-gradient(to bottom, transparent, white);
pointer-events: none;
}When line-clamp is unavailable (very old browsers, server-rendered email templates) a gradient fade gives a graceful visual hint that the text continues. Setting max-height to lines * line-height clips the text, and a pseudo-element gradient over the bottom band fades the cut-off out. The trade-off is that there is no actual ellipsis character and the gradient color must match the background, so this works best on solid backgrounds. Pair it with a 'Read more' button for full accessibility.
