Skip to main content

How to set a maximum number of lines of text with CSS

Summary: Limiting the total number lines of text within an element is something I get asked about pretty frequently, and while there are probably some complex JavaScript solutions, there is a simple, though slightly strange, way to do it with CSS only.

Kevin Powell

If you’ve ever had an article preview type component, you probably know how annoying it can be when you have varying lengths of text being pulled in.

Afterall, something like this doesn’t look fantastic:

Three cards next to each other, each one taller than the last because there is more and more text in each one

You could get away with it, but it would be nice if we could easily balance everything out.

And, we do have something in the CSS spec to do that!

Enter line-clamp

line-clamp is a strange property, in that it is part of the spec, but no browser actually supports it.

Instead, they all support the prefixed version, -webkit-line-clamp (yes, all browsers use the -webkit- prefix for this one).

It’s easy enough to use, but we do need a few extras to come along for the ride if we actually want it to work:

.selector {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

The display: -webkit-box and webkit-box-orient is a nice throwback to original flexbox drafts.

We don’t use them anymore, but browsers still support them, and in this case we need it for the line-clamp to work 🤷.

See the Pen line-clamp by Kevin (@kevinpowell) on CodePen.

It’s one of those things that looks a little bit strange if you stumble across it, and it might even be worth a quick comment to remind yourself the purpose of it if ever you use it in your code, but it does exactly what we need it to.

Link copied to clipboard