🇧🇷 VAI BRASIL!

text-overflow: ellipsis on multi-line text

by Matt Fantinel
02 Dec 2024 - 2 min read
Three dots on a flat background

Adding an automatic ellipsis to some text if it overflows its content is simple enough. You just set overflow: hidden to make sure the container doesn't scroll, and then text-overflow: ellipsis to add the ellipsis to the edge of the text.

css
.example {
	text-overflow: ellipsis;
	overflow: hidden;
}

But what if you want your text to have multiple lines, but still cut off if it's too big? For example, you want to show the excerpt of a blog post on a blog post card (just like the ones on this blog). You want it to go up to 4 lines, but if the excerpt is bigger than that, you want to add the ellipsis at the end of the 4th line.

Turns out there's a neat little trick, using some -webkit prefixed properties. Don't worry, it works on all modern browsers, including Firefox and Safari.

css
.example {
	text-overflow: ellipsis;
	overflow: hidden;
	display: -webkit-box;
	/* Set this to the max number of lines you want */
	-webkit-line-clamp: 4;
	-webkit-box-orient: vertical;
}

Here's how it looks like:

Screenshot of a card element in which a paragraph is cut off at the end of the 4th line with an ellipsis.

Taken from this StackOverflow answer.

Did this blog post change your life? Or maybe I made a mistake that ruined your day? You can always send me an email to tell me about it.

hello@fantinel.dev

Written by

Matt Fantinel

I’m a web developer trying to figure out this weird thing called the internet. I write about development, the web, games, music, and whatever else I feel like writing about!

About

Wanna get the next posts right in your (e-)mailbox?

I have a newsletter as another way to share what I write on this blog. The main goal is to be able to reach people who don't use RSS or just prefer getting their articles delivered straight into their inbox.

When subscribed, you'll receive:

  • All the blog posts I write here;
  • Monthly digests of all the cool links I share, every last day of the month;
  • No spam, no advertising. I promise.