String truncation is something I always have to Google whenever I need to use it ๐. To keep it short, this involves replacing any text beyond the desired number of lines with three dots. It's a simple yet magical solution that can save a lot of space and make your text more visually appealing.
There are two ways to handle string truncation: using the text-overflow: ellipsis
style, or the -webkit-line-clamp
property.
If you want your text to appear as a single straight line, text-overflow: ellipsis is a simple and efficient choice.
.text-box {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
*** Important note! *** This code is designed for use with fixed widths. If you want to use it with a flexbox layout, please refer Chris Coyier's tweet
text-overflow: ellipsis
is a powerful property, but it has an Achilles heel: it always truncates to one line, regardless of the length of the text. This is where the -webkit-line-clamp
property comes in for cases with multiple lines of text. By using this property, you can limit the number of lines displayed and add an ellipsis to the end of the last line, providing a more elegant solution for text truncation.
.text-box {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2; /* From which line on to truncate */
overflow: hidden;
}
While the text-overflow: ellipsis
property is useful for truncating single lines of text, the -webkit-line-clamp
property is the most effective solution for truncating multiple lines of text. However, to make it work, you need to use it in combination with the three CSS properties mentioned above. This approach enjoys strong support among browsers and is therefore the most desirable method for achieving multiline truncation.