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-clamp doesn’t work in any stable browser yet. What works in all browsers, since January 2020, is -webkit-line-clamp.
  • -webkit-line-clamp only works together with display: -webkit-box and -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 with align-items: flex-start), and put spacing in margin or on an outer element instead of padding.

Browser Support

  • Chrome

    Prefixed
    from v6
    -webkit-line-clamp
  • Edge

    Prefixed
    from v79
    -webkit-line-clamp
  • Safari

    Prefixed
    from v5
    -webkit-line-clamp
  • Safari (iOS)

    Prefixed
    from v4.2
    -webkit-line-clamp
  • Firefox

    Prefixed
    from v68
    -webkit-line-clamp

Search by feature name or code

e.g. aspect-ratio, :has(), padding-top

Try a different word or a property name.

Could not load search.