Tutorial – Truncating Overflowing Text With CSS
Weston Huggins | 02/02/23
Weston Huggins | 02/02/23
The Problem
As a web developer, you can’t always know what content your client will use on their website, and it is important to make the layout as adaptable as possible. Today, we’re going to talk about truncating overflowing text. I have found this to be especially useful for article/post links to keep their titles contained, but it can be used in many other situations!
The Solution
The solution to overflowing text lies in setting display to -webkit-box. I will demonstrate its use on the blog page of the Full Circle website, where there are links that contain a thumbnail, title, and author.
Here is the original link to the article.
I would like for the title to only take up two lines and show ellipses when it overflows the second line (note: if you are truncating only one line of text, read Other Methods below). To do this, I will add the following styling to the title div:
display: -webkit-box;
-webkit-line-clamp: 2; // Enter maximum lines here
-webkit-box-orient: vertical;
overflow: hidden;
This is the output:
How Does It Work?
The display property must be set to -webkit-box and the -webkit-box-orient property must be vertical for it to work. The -webkit-line-clamp property should be set to the maximum number of lines you would like to show.
According to caniuse, the CSS used in this tutorial is supported by all modern desktop browsers. If you are concerned about Internet Explorer compatibility, read the next section.
Other Methods
An alternative to this is using the text-overflow and white-space CSS properties. I recommend this method if you want to truncate overflowing text at only one line or if you need Internet Explorer compatibility. Here is a code example:
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
width: 200px;
Conclusion
This is a very easy solution to the constant struggle of keeping a website as adaptable as possible to whatever content gets thrown at it. Soon, I will cover how to handle a wide range of image sizes and aspect ratios while preventing distortion and layout issues. Thanks for reading!