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:
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:
overflow: hidden;
to the parent container to fix that.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):
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
.
overflow: hidden;
to the parent element.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: