How to Truncate Type at More Than One Line with Just CSS

So, I learned something new recently and wanted to share, because it's really useful and also pretty whacky.

For years I've been using this trick to visually truncate text when it wanted to break the width of a container. It worked great, as long as you were okay with it staying to one line:

See the Pen Text truncation at one line by Chip Cullen (@chipcullen) on CodePen.

.selector {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

But what about more than one line?

For years I've had designers that I work with coming to me with designs where truncation happened at a second or third line. And, I've had to tell them over and over again "Sorry, no."

Well, now, it appears, we can:

See the Pen Line clamp by Chip Cullen (@chipcullen) on CodePen.

It takes some truly bizarre CSS, though. Mainly, it takes the -webkit-line-clamp property (yes, -webkit), like so:

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

Now, the really interesting thing here is the browser support for this: Safari, Chrome, Edge and Firerfox! So, yeah, it's pretty good to go.

The one thing to note is that autoprefixer won't play nice with it for now, so you'll have to sidestep it:

.selector {
  /* autoprefixer: off */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

Progressive enhancement

You can also set up your truncation with the old method, but use this new method when the browser supports -webkit-box:

.selector {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

@supports (display: -webkit-box) {
  .selector {
    /* autoprefixer: off */
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    white-space: normal;
  }
}

Further reading: