I need to display a text as paragraph, but display only three lines and truncate the test while adding ...(three dots) in the paragraph end.
Asked
Active
Viewed 3.3k times
4 Answers
16
Calculate max length of string which can fit into 3 lines and use the following script
var maxLength = 140;
var result = yourString.substring(0, maxLength) + '...';

zavg
- 10,351
- 4
- 44
- 67
-
1How to decide the maxlength? Why 140? – Sundeep Saluja Sep 22 '14 at 11:32
-
@SundeepSaluja 140 value is just for code example (it is Twitter constant). You should empirically determine how many symbols fit into your 3 lines. – zavg Sep 22 '14 at 11:42
16
I use the same logic than @zavg with some improvements:
- Use the single
…
character. - Respect the maximum size.
function truncate(source, size) {
return source.length > size ? source.slice(0, size - 1) + "…" : source;
}
var res = truncate('Truncate text to fit in 3 lines', 14);
console.log(res);

aloisdg
- 22,270
- 6
- 85
- 105
15
.class-name {
display: block;
white-space: nowrap;
width: 15em;
overflow: hidden;
text-overflow: ellipsis;
}
<div style="height: 15vh; padding: 10px;
background:#dee0e5">
<span>Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum is simply dummy text of the printing and typesetting industry</span>
</div>
<div style="height: 15vh;padding: 10px; margin-top:5px;
background:#aff8af">
<span class="class-name">Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum is simply dummy text of the printing and typesetting industry</span>
</div>

Israt Jahan Simu
- 1,040
- 13
- 7
1
Try the following css property:
.your-class-name {
text-overflow: ellipsis;
-webkit-line-clamp: 3;
line-clamp: 3;
}

closure
- 7,412
- 1
- 23
- 23