Line clamp… I love you

About a 3 minute read

Written by on

#css

Multi-line truncating. Pure CSS.

For as long as I can remember in my coding career, multiple line truncating has always been a thorn in the side. It’s really something that you just try to avoid at all costs, you know? I mean, sure, you can count characters and truncate it that way with JavaScript or on the server side…but, what if that text has more/less space at different viewports? It turns into a mess of complicated.

I recently ran into this issue at my work and only then did I discover the wonderful, wonderful experience that is line clamp. Line clamp gives us a pure CSS way to truncate multiple lines of text. Yes, you read that correctly. We can handle it in CSS!

div {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

Awesome, right? All you have to do is adjust the -webkit-line-clamp property to the number (integer) of lines you want. You can even do 1, if you want.

Wait a minute…webkit?

Yeah, webkit. Line clamp is only available with the webkit prefix, which seems like a red flag, right? Well…support is actually really damn good. It’s 95.33% supported at the time of writing, which is insane. Why the hell isn’t this adopted yet?! Someone above my pay grade can probably answer that.

The weird things here are the display, which is -webkit-box, and the -webkit-box-orient property. I was doing some Googlin’ around, and didn’t really find anything on these guys, besides the fact that they are webkit. I found one thing talking about box-orient being deprecated, but -webkit-line-clamp doesn’t work without it. Besides those two things, it’s pretty run-of-the-mill as far as properties.

It’s worth noting that -webkit-box is a block level declaration, so if you are wanting to keep it inline, you’ll have to use -webkit-inline-box. I haven’t worked with the inline version personally, but messing around with it in CodePen shows that it yields expected results.

Minor Issues

I did run into some minor issues when using this in the real world. There’s a pretty easy workaround, but if you add any sort of padding to the element you are trying to line-clamp, it appears to break the truncating. You can see an example of this below.

The workaround is simple, just add a child element. That child element will have the truncating styling, whereas the parent will have the padding.

I hope this helps someone out there, as it helped me.