How to truncate text to multiple lines using CSS?
12
I have a large block of text that spans multiple lines, but I want to truncate it to display only a specific number of lines with an ellipsis (...) at the end.
What CSS properties and techniques can I use to achieve this multi-line text truncation effect?
1 Answer
18
There are several CSS techniques to truncate text across multiple lines. Here are the most effective methods:
Method 1: Using -webkit-line-clamp (Recommended)
.truncate-multiline {
display: -webkit-box;
-webkit-line-clamp: 3; /* Number of lines to show */
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
Method 2: Using CSS Grid
.truncate-grid {
display: grid;
grid-template-rows: repeat(3, 1fr); /* 3 lines */
overflow: hidden;
text-overflow: ellipsis;
}
Method 3: Using Flexbox with max-height
.truncate-flex {
display: flex;
flex-direction: column;
max-height: 4.5em; /* Approximate height for 3 lines */
overflow: hidden;
text-overflow: ellipsis;
line-height: 1.5;
}
Browser Support: The -webkit-line-clamp
method has excellent modern browser support and is the most reliable solution. For older browsers, consider using JavaScript as a fallback.