0
0
Tailwindmarkup~5 mins

Text overflow and truncation in Tailwind

Choose your learning style9 modes available
Introduction

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.

Showing a short preview of a long article title in a card.
Displaying usernames in a fixed-width menu without breaking layout.
Limiting product names in a list to keep the design clean.
Showing messages in a chat bubble without overflow.
Keeping table columns tidy when text is too long.
Syntax
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.

Examples
This box is 12rem wide and the text will show dots if it is too long.
Tailwind
<div class="w-48 truncate">This is a very long text that will be cut off with dots.</div>
The paragraph will not grow beyond the max width and will truncate overflow text.
Tailwind
<p class="max-w-xs truncate">Another example with max width and truncation.</p>
Text fits inside the 8rem wide span, so no dots appear.
Tailwind
<span class="inline-block w-32 truncate">Short text that fits.</span>
Sample Program

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.

Tailwind
<!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>
OutputSuccess
Important Notes

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.

Summary

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.