Skip to main content

How to implement multiple line ellipsis in CSS

· 2 min read

We all know how easy it is for CSS to make a line of text overflow the ellipsis. But how do we make it work for multiple lines?

CSS single line ellipsis

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

Because of the white-space: nowrap property, the browser will not wrap the text. So the browser will not break the line. This method is not work for multiple lines.

-webkit-line-clamp

Fortunately, modern browsers offer a new CSS property. -webkit-line-clamp allow us to implement multiple line ellipsis.

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

It's very simple, right? The above example implements plain text ellipses, assuming we want to implement an HTML tag? How do we do that?

multiple line ellipsis with HTML tags

Assume we have a html structure like this:

<div class="card">
<span>js</span>
<span>css</span>
<span>webpack</span>
<span>android</span>
<span>flutter</span>
</div>

and the css

.card {
padding: 10px;
width: 160px;
border: 1px solid #afafaf;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

span {
padding: 4px 10px;
color: #FFF;
background-color: #afafaf;
}

Pretty gross, right? So let's optimize it. we add display: inline-block; to span class.

It's working really well right now. 💯