Adding Ellipsis to Text Using Only HTML and CSS

Photo by Ben White on Unsplash

Adding Ellipsis to Text Using Only HTML and CSS

Text truncation, often represented by ellipsis (…), is a useful technique to control the display of lengthy text content within limited space. With just HTML and CSS, you can easily achieve this effect. In this blog post, we'll explore how to add ellipsis to text using these two fundamental web technologies.

The Challenge

Imagine you have a website or application that displays various content, such as article titles, event descriptions, or product names. In some cases, these texts might be too long to fit comfortably within their designated containers. To maintain a clean and user-friendly layout, it's essential to truncate the text and show an ellipsis when it overflows the available space.

The Solution

To accomplish this, we can use a combination of CSS properties to control the text's display. Here's a step-by-step guide:

1. Create Your HTML Structure

Begin by setting up your HTML structure. For this example, we'll have a container div with two child divs, each containing different text elements.

<div>
    <div class="ellipme">chelsea vs arsenal</div>
    <div class="ellipme">21 Sep 17:45 INT Club UEFA Champion league</div>
</div>

2. Define CSS Class for Text Truncation

Next, create a CSS class that will apply the text truncation and ellipsis effect. In our example, we've named it .ellipme.

.ellipme {
    width: 200px;        /* Set a fixed width for the container */
    white-space: nowrap; /* Prevent text from wrapping */
    overflow: hidden;    /* Hide any overflowing text */
    text-overflow: ellipsis; /* Display an ellipsis (...) for truncated text */
    color: black;        /* Define the text color */
    border: 1px solid black; /* Add a border for visibility (optional) */
}

3. CSS Properties Explanation

  • width: Set a fixed width for the container to restrict the text within this width.

  • white-space: nowrap: Prevent text from wrapping onto the next line.

  • overflow: hidden: Hide any text that exceeds the specified container width.

  • text-overflow: ellipsis: Display an ellipsis when the text is truncated.

  • color: Define the text color (customize as needed).

  • border: Add a border (optional) to make the container visually distinct.

4. Apply the CSS Class

Finally, apply the .ellipme class to the HTML elements containing the text you want to truncate with ellipsis.

Conclusion

Adding ellipsis to text using only HTML and CSS is a straightforward and effective way to improve the readability and aesthetics of your web content. It allows you to control text overflow while maintaining a clean and organized layout. Whether you're building a blog, e-commerce site, or any web application, text truncation with ellipsis can enhance the user experience and make your content more accessible.