As part of this blog lets see two ways in which you can truncate a text using CSS
1) Truncate a single line text using ellipsis
.truncate-ellipsis {
width: 350px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: block;
}
With text-overflow , ellipsis can be applied to single line of text, provided the following conditions are met. [ For truncating after multiple lines, keep reading 😉 ].
- the element must have > width , max-width or flex-basis(if using flex)
- the element must have property > word-wrap: nowrap
- overflow property should have value other than visible . > eg: overflow: hidden;
- must have display value as block, inline-block or any other equivalent such as flex item etc. display:inline will not work here. > eg: display: inline-block;
Did you know that you can reverse the direction of the truncation using the CSS direction property?
direction: rtl; //show from right to left
The direction property will truncate the text in the start of the line and show the end of the paragraph instead.
2) Truncate text after multiple lines using line-clamp
.truncate-line-clamp {
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
width: 250px;
overflow: hidden;
}
With line-clamp text can be truncated after multiple lines, whats even more interesting is you can truncate it by specifying the line number where you want to truncate it.
eg: -webkit-line-clamp: 3; will truncate start truncating the text from the third line.
Below are the list of conditions which should be met in order to make this work.
- display property should be webkit-box > eg: display: -webkit-box;
- webkit-line-clamp value should be specified , value should be greater than 0. > eg: webkit-line-clamp: 3;
- box-orient should be set to vertical > eg: -webkit-box-orient: vertical;
- overflow property should have value hidden . > eg: overflow: hidden;
Browser Compatability: webkit-line-clamp at the moment is not supported in IE.
For detailed information refer: caniuse.com
Codepen:
The below codepen will show you a live preview of the above two methods will look.
https://codepen.io/kpattalam/pen/jOBXvyg
References - MDN docs
Lets connect on Twitter | LinkedIn for more web development related tips.
Top comments (0)