line-clamp
Cuts text off after a given number of lines and adds "…" at the end. Multi-line truncation you used to do by trimming characters in JavaScript can be written in CSS alone.
Modern approach
Set the number of lines, and the overflowing part is hidden with ”…” added. Since no characters are removed, the full text stays in the HTML.
.excerpt {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}Legacy approach
Multi-line truncation only worked in some browsers, so JavaScript trimmed one character at a time and added ”…” once the text fit in three lines. Every time the viewport width changed, it also had to restore the original text and start over.
.excerpt {
line-height: 1.5;
max-height: 4.5em;
overflow: hidden;
}
for (const excerpt of document.querySelectorAll('.excerpt')) {
const text = excerpt.textContent
const clamp = () => {
excerpt.textContent = text
let end = text.length
while (excerpt.scrollHeight > excerpt.clientHeight && end > 0) {
end--
excerpt.textContent = text.slice(0, end) + '…'
}
}
clamp()
window.addEventListener('resize', clamp)
}Things to watch when replacing
- Unprefixed
line-clampdoesn’t work in any stable browser yet. What works in all browsers, since January 2020, is-webkit-line-clamp. -webkit-line-clamponly works together withdisplay: -webkit-boxand-webkit-box-orient: vertical. This combination of three is defined in the specification despite the prefixes, and will keep working.- If the element gets taller than the given number of lines, the hidden lines show up. Don’t set
height, keep it from stretching inside Flexbox or Grid (for example withalign-items: flex-start), and put spacing inmarginor on an outer element instead ofpadding.
Browser Support
Chrome
Prefixed
from v6-webkit-line-clampEdge
Prefixed
from v79-webkit-line-clampSafari
Prefixed
from v5-webkit-line-clampSafari (iOS)
Prefixed
from v4.2-webkit-line-clampFirefox
Prefixed
from v68-webkit-line-clamp