Truncating long text and showing an ellipsis (three dots) is a common requirement when designing web pages with limited space. With CSS, you can achieve this effect without using any JavaScript. In this blog post, we will discuss how to create a text ellipsis using CSS.
Getting Started
To create a text ellipsis, we will use the following CSS properties:
- white-space: This property defines how the white space inside an element should be handled. For our ellipsis effect, we will set it to nowrap.
- overflow: This property specifies what should happen when the content overflows the element’s box. We will set it to hidden so that any overflowing content will be clipped and not visible.
- text-overflow: This property specifies how the text content should be displayed when it overflows the element’s box. We will set it to ellipsis to show a horizontal ellipsis as the indicator of clipped text.
- max-width (optional): This property sets the maximum width of an element. You can use this property to limit the width of the element containing the text, forcing the ellipsis effect when the text overflows.
Example
Let’s assume we have a div element containing some long text, and we want to create a single-line ellipsis effect for it. Here’s how you can apply the CSS properties mentioned above:
.ellipsis { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; /* Adjust this value as needed */ }
Now, add the ellipsis class to your div element:
<div class="ellipsis"> This is a very long text that will be truncated with an ellipsis effect when it exceeds the maximum width of 200 pixels. </div>
With these simple CSS rules, you can create a single-line ellipsis effect for any text inside an element. This approach works well with most modern browsers and does not require any JavaScript.
Conclusion
In this blog post, we’ve discussed how to create a text ellipsis using CSS. By applying the white-space, overflow, text-overflow, and optional max-width properties, you can easily truncate long text and show an ellipsis when the content exceeds the specified width. This approach is lightweight and compatible with most modern browsers.