I am working on a project where I need to display text in a container. The text can sometimes be long, and I want it to be truncated with an ellipsis ("…") at the end when it overflows the container. I’m using Tailwind CSS for my styling, and I am unsure about the correct approach to implement the "three dots" effect on text that overflows. I’ve tried applying the text-overflow, overflow, and white-space properties manually in CSS, but I want to know how to achieve this effect using Tailwind CSS.
I expect that by applying the appropriate Tailwind classes, the text will be truncated properly with an ellipsis when it overflows the container’s boundaries.
Here’s a basic example of what I’ve attempted:
<div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 200px;">
This is a long text that will be truncated with an ellipsis.
</div>
But I’d like to know if there’s a cleaner way to implement this using Tailwind’s utility classes.
I tried manually applying the following styles to a div element to truncate the text and add the ellipsis effect when it overflows:
<div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 200px;">
This is a long text that will be truncated with an ellipsis.
</div>
I expected this to work as I have seen these CSS properties used together in standard CSS to create the ellipsis effect. However, I would prefer a more Tailwind CSS-centric solution using its utility classes.
3
Answers
You can achieve the "three dots" (ellipsis) effect in Tailwind CSS using the truncate utility class, which combines the necessary styles (overflow: hidden; text-overflow: ellipsis; white-space: nowrap) to truncate the text and add an ellipsis when the text overflows its container.
Here’s the correct Tailwind CSS implementation:
By using this combination of classes, you don’t need to manually write the CSS properties, and it makes your code cleaner and more maintainable.
You can use a custom width with Tailwind’s arbitrary value syntax:
In tailwindcss you can apply the width to the element with
.truncate
class.https://play.tailwindcss.com/BGWy5P6AIb