Tag logo

How to truncate texts in multiple lines in CSS?

May 22, 2024/
#css
/-1 min

The SCSS implementation is as follows:

1@mixin truncate-lines($line-count, $breakType: word) {
2  overflow: hidden;
3  text-overflow: ellipsis;
4  display: -webkit-box;
5  white-space: pre-wrap;
6  -webkit-box-orient: vertical;
7  -webkit-line-clamp: $line-count;
8
9  @if $breakType =="word" {
10    word-break: break-word;
11  }
12
13  @else if $breakType =="letter" {
14    word-break: break-all
15  }
16
17  @else {
18    @error "Unknown break type #{$breakType}.";
19  }
20}
21
22.title {
23  @include truncate-lines(2, "letter")
24}

The Less implementation is as follows:

1.truncate-lines(@lineCount; @breakType: "word") {
2  overflow: hidden;
3  text-overflow: ellipsis;
4  display: -webkit-box;
5  white-space: pre-wrap;
6  -webkit-box-orient: vertical;
7  -webkit-line-clamp: @lineCount;
8
9  & when (@breakType = "word") {
10    word-break: break-word;
11  }
12
13  & when (@breakType = "letter") {
14    word-break: break-all;
15  }
16}
17
18.title {
19  .max-lines(2, "letter");
20}