Tip #33: Automatically add ellipsis with the truncate utility

  • — TailwindCSS

  • 1 min. read

  • — 2/25/2023

When working with large blocks on text on the frontend we sometimes want to truncate that text with an ellipsis (the three ...).

Taking something like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vel elit scelerisque mauris pellentesque pulvinar. Ornare suspendisse sed nisi lacus. Posuere sollicitudin aliquam ultrices sagittis orci a scelerisque purus. Suspendisse interdum consectetur libero id faucibus. 

and turning it into:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor...

This is especially useful for content we don't directly control such as user bios, product descriptions, reviews, etc.

Typically you would create a button that says "read more" to expand the text to its full form, but today let's just focus on building the text so it automatically truncates without us having to write anything to complex.

We can easily create this using TailwindCSS's truncate utility.

In the background, trucate will set the following CSS properties:

.truncate{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

To set it, just add truncate to any text element on your design. Make sure you also specify a width for that piece of text or else it won't work!

<p class="truncate w-11/12">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vel elit scelerisque mauris pellentesque pulvinar. Ornare suspendisse sed nisi lacus. Posuere sollicitudin aliquam ultrices sagittis orci a scelerisque purus. Suspendisse interdum consectetur libero id faucibus.</p>

Here's what that final result would look like:

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!