In this tutorial, we will explore how to apply an ellipsis to text in CSS. An ellipsis is a series of three dots (…) used to indicate that some text has been truncated or omitted.
Introduction to Ellipsis
The text-overflow
property in CSS allows you to specify how to handle overflowed text. One of the possible values for this property is ellipsis
, which will display an ellipsis at the end of the text if it overflows its container.
Applying Ellipsis to Single Line Text
To apply an ellipsis to a single line of text, you need to meet certain requirements:
- The element must have a
width
,max-width
, orflex-basis
set. - The
white-space
property must be set tonowrap
. - The
overflow
property must be set to a value other thanvisible
. - The element must be a block-level element, such as a
div
orp
, or an inline-block element.
Here is an example of how to apply an ellipsis to a single line of text:
p {
width: 200px;
white-space: nowrap;
overflow: hidden;
display: inline-block;
text-overflow: ellipsis;
}
This will truncate the text and display an ellipsis at the end if it overflows its container.
Applying Ellipsis to Multiline Text
Unfortunately, CSS does not have a built-in way to apply an ellipsis to multiline text. However, there are several workarounds available:
- Using
-webkit-line-clamp
property (only works in WebKit-based browsers) - Using JavaScript libraries such as jQuery dotdotdot…
- Using pure CSS solutions that involve wrapping the text in multiple elements and applying
overflow: hidden
to each element.
One example of a pure CSS solution is to use the following code:
p {
display: -webkit-box;
max-width: 200px;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
This will truncate the text after four lines and display an ellipsis at the end. Note that this solution only works in WebKit-based browsers.
Conclusion
Applying an ellipsis to text in CSS can be achieved using the text-overflow
property for single line text, but requires workarounds for multiline text. By understanding the requirements for applying an ellipsis and using the available workarounds, you can effectively truncate text and display an ellipsis at the end.
Example Use Case
Suppose you have a paragraph of text that you want to truncate after four lines and display an ellipsis at the end:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh.</p>
You can use the following CSS to apply an ellipsis:
p {
display: -webkit-box;
max-width: 200px;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
This will truncate the text after four lines and display an ellipsis at the end.