Sometimes text is too long to fit in a small space. We use text overflow and truncation to cut the text nicely and show it with dots.
Text overflow and truncation in Tailwind
class="truncate"The truncate class in Tailwind applies overflow: hidden;, white-space: nowrap;, and text-overflow: ellipsis; to cut off text with dots.
Use it on block or inline-block elements with a fixed width or max-width.
<div class="w-48 truncate">This is a very long text that will be cut off with dots.</div><p class="max-w-xs truncate">Another example with max width and truncation.</p><span class="inline-block w-32 truncate">Short text that fits.</span>This page shows three boxes with different widths. The first two have long text that gets cut off with dots. The last one has short text that fits fully.
We use Tailwind's truncate class and fixed widths to control the text overflow.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Text Overflow and Truncation</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="p-6"> <h1 class="text-xl font-bold mb-4">Text Overflow and Truncation Example</h1> <div class="w-48 border border-gray-400 p-2 mb-4 truncate" aria-label="Truncated text example"> This is a very long text that will not fit in the box and will be truncated with dots at the end. </div> <p class="max-w-xs border border-blue-400 p-2 truncate" aria-label="Another truncated text"> Another example with a max width set and text that is too long to fit inside. </p> <span class="inline-block w-32 border border-green-400 p-2 truncate" aria-label="Short text example"> Short text fits. </span> </body> </html>
Make sure the container has a fixed width or max-width for truncation to work.
Use aria-label to describe truncated text for screen readers.
Truncation only works on single-line text. For multi-line truncation, other techniques are needed.
Use Tailwind's truncate class to cut off long text with dots.
Set a fixed width or max-width on the container for truncation to work.
Always consider accessibility by labeling truncated text.