LogRocket Blog

How to truncate text in CSS (single and multi-line)

thumbnail

Table of Contents

  1. Single-line Text Truncation with CSS
  2. Multi-line Text Truncation with CSS
  3. Quick Snippet: Truncate Text on One Line
  4. Using CSS to Truncate Text
  5. Issues with Using text-overflow: ellipsis in a Flexbox
  6. Applying Multi-line Text Truncation with Tailwind CSS

Single-line Text Truncation with CSS

To truncate text in a single line using CSS, follow these steps:

  • Unwrap the text using white-space: nowrap
  • Clip the text with overflow: hidden
  • Use text-overflow: ellipsis for automatic ellipsis indicator

Here's a quick snippet for single-line text truncation:

.single-line-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Multi-line Text Truncation with CSS

For multi-line text truncation in CSS, you can use the following properties:

  • Use display: -webkit-box; with -webkit-line-clamp to specify the number of lines
  • Hide overflowing text with overflow: hidden
  • Set text-overflow: ellipsis for truncation indicator

Here is a CSS setup for multi-line text truncation:

.multi-line-truncate {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* Number of lines to show */
  overflow: hidden;
  text-overflow: ellipsis;
}

Quick Snippet: Truncate Text on One Line

If you need a quick way to truncate text on one line, you can use the following CSS snippet:

.single-line-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Using CSS to Truncate Text

To truncate text with CSS, you can use text-overflow: ellipsis for single-line truncation and -webkit-line-clamp for multi-line truncation. Ensure the parent container's width is set to determine truncation.

Issues with Using text-overflow: ellipsis in a Flexbox

When using text-overflow: ellipsis inside a flexbox child element, ensure the child has a specified width to prevent layout issues.

Applying Multi-line Text Truncation with Tailwind CSS

Tailwind CSS offers utility classes for truncating text, making it easy to apply multi-line truncation effects. Use classes like line-clamp-3 to specify the number of visible lines for truncation.