- Published on
How to Truncate Text with Ellipsis in Tailwind CSS
- Authors
- Name
- Ripal & Zalak
Tailwind CSS: How to Use text-overflow: ellipsis
When working with Tailwind CSS, you may want to truncate long text with an ellipsis (...) to keep your UI clean. In standard CSS, this is achieved using:
.element {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
Solution in Tailwind CSS
Tailwind provides a built-in utility class .truncate that applies the necessary styles automatically:
<div class="w-32 truncate">
This is a long text that will be truncated with an ellipsis if it overflows.
</div>
What Does .truncate Do?
The .truncate class in Tailwind applies the following styles:
overflow: hidden;white-space: nowrap;text-overflow: ellipsis;
Custom Multi-Line Truncation
If you need to truncate text after multiple lines, use the line-clamp utility in Tailwind CSS (available since v3.3):
<p class="line-clamp-2">This text will be truncated after two lines, adding an ellipsis.</p>
For older versions of Tailwind, install the plugin:
npm install @tailwindcss/line-clamp
Then, add it to tailwind.config.js:
module.exports = {
plugins: [require('@tailwindcss/line-clamp')],
}
Custom Utility Class for More Control
If you need a more customizable approach, define your own utility classes:
.ellipsis {
@apply overflow-hidden text-ellipsis whitespace-nowrap;
}
Use it in your HTML:
<div class="ellipsis w-40">Custom truncated text example.</div>
FAQ
1. Why isn’t truncate working?
Ensure that your element has a fixed width (w-32, w-40, etc.), as Tailwind’s .truncate class requires a width to work.
2. Can I use truncate with flexbox?
Yes, but make sure the flex container does not force content expansion.
3. How do I truncate text inside a grid or flex container?
Apply .truncate along with a fixed width to ensure proper truncation within dynamic layouts.
4. How do I truncate multiple lines without line-clamp?
Use CSS properties like display: -webkit-box; and -webkit-line-clamp in a custom class.
