This site is under construction

You probably already noticed that this page looks very bare. I'm working on a new design and will gradually make adjustments to make this site a little more appealing and accessible. If you notice something that is totally broken, feel free to contact me.

Skip to content

Cross Browser Multiline Truncating

21 Mar 2020

Truncating Strings with Ellipsis is a common way to handle longer content. This is an example of how you can deal with multiline truncating.

Single Line Truncating

Single line truncating is a common way to handle longer content and it is possible with CSS only. Truncating multiple lines is a bit harder.

Multi Line Truncating

It is not impossible.. but the solutions described so far, e.g. pure CSS with pseudo Elements ::before, ::after and line-height for measuring or plenty JavaScript based Solutions, are not the perfect way to deal with multiline truncating. Fortunately there is a proper way to handle this common problem:

See the Pen Multiline Truncating (Cross Browser) by Jonas Fährmann (@jfaehrmann) on CodePen.

What is happening here?

All examples are in fact identical, except for value of display for the container. The third example is a fallback for our beloved Internet Explorer. But more about that later.
All the magic for the multiline truncating is happening within the following lines:

.block-container,
.flex-container {
  display: -webkit-box;
  -webkit-line-clamp: var(--line-clamp);
  -webkit-box-orient: vertical;
  overflow: hidden;
}

And as you can see line-clamp is mostly supported across all modern browsers. line-clamp is a undocumented CSS property that will contain text to a given amount of lines when used in combination with display: -webkit-box. In this demo there is a line-clamp of 3. If you change the CSS Variable --line-clamp you can see that the amount of lines will change. Perfect! Well.. and then there is the IE.

Fallback IE
For the IE we have to add a little trick that calculates the height of the container:

.ie-block-container {
  height: calc(var(--line-height) * var(--multiplicator));
}

More articles and notes