CSS

Easiest Way to Truncate Text With Ellipsis in CSS

Learn to truncate text and add ellipsis at the end using CSS. For both, single-line and multi-line text.

· 3 min read
Easiest Way to Truncate Text With Ellipsis in CSS

So your designer has asked you to add the three dots at the end when the text doesn't fit, and you have no clue how to do that?

Don't worry, it's super simple to do with CSS.

By the way, those three dots at the end are called ellipsis.


Real quick - would you like to master CSS and learn Web Development? If so, be sure to check out the platform I recommend to learn coding online:

Learn Coding Online
Here’s the platform I recommend if you want to learn Web Development online.

Single-line ellipsis

Use text-overflow: ellipsis; to automatically truncate the text when it overflows the container and add the three dots at the end.

The element needs to get resized and the text has to stay in one line for the ellipsis to show up, so here are all 3 CSS lines you need:

.ellipsis {
  text-overflow: ellipsis; /* enables ellipsis */
  white-space: nowrap; /* keeps the text in a single line */
  overflow: hidden; /* keeps the element from overflowing its parent */
}
Single-line ellipsis using CSS.
📣
The parent container often allows its contents to overflow, making the ellipsis not show up. Add overflow: hidden; to the parent container to fix that.
Example of single-line ellipsis in practice.

Multi-line ellipsis

You will soon find, that text-overflow: ellipsis; doesn't work when the text wraps to an extra line.

To truncate multi-line text and add an ellipsis at the end of the last line use the experimental -webkit-box box model (don't worry it's supported in all major browsers):

.multiline-ellipsis {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* start showing ellipsis when 3rd line is reached */
  white-space: pre-wrap; /* let the text wrap preserving spaces */
}
Multi-line ellipsis using CSS.

Control how many lines to show with -webkit-line-clamp. It is important to let the text wrap by setting the white-space property to pre-wrap or normal.

📣
Same as before, the parent container needs to clip its children. Add overflow: hidden; to the parent element.
Example of multi-line ellipsis in practice.

Conclusion

It's trivial to truncate the overflowing text and add an ellipsis at the end of a single line. Adding an ellipsis for multiline text is a bit more tricky, so this post should help you.

You can find the code examples for this article on my GitHub: https://github.com/vincaslt/twitter-code/tree/main/src/ellipsis

Since you're learning CSS tricks, why not go through my practical CSS guide? It will take only 5 minutes, but it will teach you all of the CSS you need in practice:

Practical CSS Guide for Busy Developers
Why waste time memorizing stuff you will never use? Here’s the only CSS guide you will ever need to start styling web pages.