CSS: Truncating text that is too long with text-overflow

NicolasBrondinBernard

Author
@NicolasBrondinBernard

In life, sometimes, you have to know how to keep it short...

Article published on 12/11/2020, last updated on 10/08/2026

An image is worth a thousand words, sure, but sometimes we still need to use words! And when our titles are too long, when they overflow, wrap onto a new line and break the whole design of the application, it's annoying!

Of course there's always the possibility of restricting them to a certain number of characters in javascript, but the problem is that two texts with the same number of characters won't necessarily be the same size when displayed!

The two lines below, for example, are each made up of 10 characters:
1111111111
0000000000

The ideal solution is therefore to be able to handle this problem from a graphical point of view, and fortunately, in CSS3 the text-overflow attribute appeared which will allow us to fix this.

Text-overflow: ellipsis

First of all, I'd like to point out that the text-overflow property is very well supported by all browsers, even internet explorer, so feel free to use it as much as you like!

Screenshot of the caniuse.com website

Text-overflow will allow us to specify to the browser's rendering engine how it should handle text that overflows its container.

There are several values for this attribute, but the one that will be most useful to us is "ellipsis" which forces the browser to add an ellipsis "..." at the end of the truncated string.

Note that for the property to work, you also need to add two other properties to our element:

  • "white-space: nowrap" to prevent our text from wrapping onto multiple lines
  • "overflow: hidden" to prevent our text from spilling out of the container

Here's a minimal working example (the container size was chosen arbitrarily, it doesn't need to be a fixed size):

/* style.css*/
.short-text-container {
  width: 200px;
}
.short-text {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

I am a text that's too long to write

And there you have it, you'll now be able to manage your titles and short texts in a simple way and with a perfectly readable result!


Spencer Davis sur Unsplash

Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet