How to Truncate Text with Ellipsis in Tailwind CSS
Introduction
When displaying dynamic content in a table or a list, text can sometimes overflow beyond the available space, making the UI look messy. A common solution is to truncate the text with an ellipsis (…) to ensure a clean and responsive design.
In this article, we will explore how to achieve this using Tailwind CSS in a React and Next.js project.
Why Use Text Truncation?
✅ Keeps the UI clean and organized
✅ Prevents text from breaking layout
✅ Improves readability in tables and cards
✅ Enhances user experience on small screens
1️⃣ Basic CSS Approach
A standard CSS solution for text truncation looks like this:
.truncate-text {
width: 183px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: block;
margin-top: 9px;
}
While this works, it’s not ideal in a Tailwind project because it doesn’t leverage Tailwind’s utility-first approach.
2️⃣ Tailwind CSS Solution
Instead of writing custom CSS, you can achieve the same effect using Tailwind’s utility classes:
<span className=”block w-[183px] whitespace-nowrap overflow-hidden text-ellipsis mt-[9px]”>
{order.customer}
</span>
3️⃣ Using Text Truncation in a Table
When working with tables, you may want to truncate long customer names but still display the full name on hover. Here’s how to do it in a table cell:
<td className=”px-4 py-6 whitespace-nowrap text-center text-dewTablecolhighlight”>
<span className=”block w-[183px] whitespace-nowrap overflow-hidden text-ellipsis mt-[9px]” title={order.customer}>
{order.customer}
</span>
</td>
Explanation:
The title={order.customer} attribute ensures that users can see the full name when they hover over the truncated text.
This makes it accessible and user-friendly.
4️⃣ Responsive Truncation with Tailwind
If you want the text to truncate only on small screens but display fully on larger screens, use responsive classes:
<span className=”block w-[183px] sm:w-auto whitespace-nowrap overflow-hidden text-ellipsis mt-[9px]”>
{order.customer}
</span>