The easiest way to limit text to n lines is to use line-clamp
. N can be any positive number, but it will be two or three lines most of the time. On my blog, I'm using line-clamp
in all post-type components to ensure that it will have the same height as siblings.
One-line truncation
To truncate only one line we can use:
.truncate {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
White-space and overflow will do the job, while text-overflow will add three dots at the end of the line.
than one line?
Multiple lines truncation
The easiest way is to use this snippet:
.truncate {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; /* number of lines to show */
line-clamp: 2;
-webkit-box-orient: vertical;
}
We are using multiple CSS properties:
overflow: hidden;
text-overflow: ellipsis; - optional, it will add three dots at the end of the trimmed line
display: -webkit-box;
-webkit-line-clamp: 2; - here we can specify how many lines we want to show to the user
line-clamp: 2;
-webkit-box-orient: vertical;
Browser Support
According to Can I Use line-clamp
truncation is supported by all major browsers except IE11 and Opera Mini.
IE-11 Support
To support IE 11, we can use max-height
instead of line-clamp
.
.truncate {
display: block;
max-height: 3.6em;
line-height: 1.8em;
}
The line-height
is set to 1,8em and max-height
to 3,6em. Max lines are calculated in this way: 3,6em divided by 1,8em equals 2 lines.
Codepen demo to play with: