Multiple Line Ellipsis CSS Effect

Multiple Line Ellipsis CSS Effect

joel.
CSS

Nov 15, 2015

A lot of times text can really destroy the design of your site, especially when there is no way of knowing how much text each element might contain. You might design your site to look good with just a few lines of text, but much later the entire lorum ipsum is displayed. The way to fix this is by adding css to an element which will limit the visibility of the text after a certain point. A visually appealing way of doing this is to cut the text at a certain point and add an ellipsis.

What's an Ellipsis?

If you don’t know what ellipsis is you can learn more about it here. Basically it’s the … at the end of text which lets the reader know that the text/thought has been cutoff. In this post we will see how to add both single and multiple line ellipsis effects using purely CSS.

Single Line Ellipsis

The following block of code will create the ellipsis effect once the element reaches the width of the parent element:

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

Multiple Line Ellipsis

If you notice, the last effect is great for adding an ellipsis to single lines of text, but the text won’t break into multiple lines because of the line that states white-space: nowrap;. This forces the text to stay on the same line no matter how long it is. In order to fix this and be able to show multiple lines of text before adding the ellipsis we must use the following class instead:

.block-ellipsis {
  display: block;
  display: -webkit-box;
  max-width: 100%;
  height: 43px;
  margin: 0 auto;
  font-size: 14px;
  line-height: 1;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

To make this code work properly we must do some calculations. The height property is equal to the number of lines desired multiplied by the font-size plus 1px to account for character descenders.

So in this example the font-size is set to 14px, and I wanted to show 3 lines of text before adding the ellipsis. So 3 x 14 + 1 = 43, which means the total height will be 43px. Isn't math fun? 🤓

Note! The ellipsis effect requires webkit, which means if someone views it using a browser that does not support webkit then they will not see the ... but the text will still be cut off at the correct point, so this effect still works on all major browsers.

one last thing

Just a quick note, for these to work they must be inside a div with a set width, if the parent element has no width then the text will just continue on forever and the effect won’t work. In the example above, the parent’s width was set at 300px. So once the text reached 300px, the ellipsis effect took over. Pretty simple but super useful!

before you go, spread the word

joel.

Father. Husband. Web Developer at Deseret Book. Runner. Real Salt Lake fan.

join the newsletter

or don't, what do we care? but if you do, we promise to send cool stuff