Multi-line text truncation
-webkit-line-clamp
Baseline widely available
Truncating text after a fixed number of lines, with an ellipsis, used to mean measuring rendered line height in JavaScript and cutting the string by hand. The line-clamp property does it in CSS, no measuring and no re-running on resize or font load. Only the vendor-prefixed form is safe to use today; the unprefixed property is still landing.
When this applies
Truncating a block of text to a fixed number of lines with an ellipsis.
The native approach
.excerpt {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}When the dependency is still right
An answer that always says "the platform covers it" is worse than no answer. These are the cases where this one does not hold.
- You need to combine this with a display value other than -webkit-box on the same element, since the prefixed property requires it.
- You need to know the exact character or word where the text was cut, for something like a 'read more' link that continues from that point.
- You're relying on a build tool to add this prefix for you and it doesn't; -webkit-line-clamp still needs to be written by hand, autoprefixer tools do not treat it as one they add automatically in every configuration.