logo

Truncate text with CSS

February 19, 2024

Truncation of the text is often used when you want to prevent text from wrapping on a new line.

To truncate text with CSS, you can use the the white-space property with the value nowrap in combination with overflow: hidden and text-overflow: ellipses.

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

Explanation

  • white-space: nowrap - the white-space property is used to control how white space inside the element is handled. The value nowrap tells the browser to display the text inside the .text-ellipsis element on a single line without wrapping it on a new line.
  • overflow: hidden - the overflow property specifies what should happen if the content of an element does not fit its box (it overflows). The value hidden means that any content that exceeds the bounding box of the .text-ellipsis element will be clipped of and won’t be visible.
  • text-overflow: ellipsis causes the browser to display an ellipsis () at the point where the text is cut off to indicate to the user that there is more text than what is currently visible.

CSS Demo

Below is an example of how you would truncate long text inside heading 1 and text inside a table. This technique is useful in case you want to ensure that the text in each cell does not wrap and instead shows an ellipsis if it is too long to fit in the cell.

Your JS is turned off. Please turn it on to see the CodePen. Here's a screenshot from the Pen

Try reload the page, our check out the pen on CodePen

In the case of the table cell, I’ve created two utility classes, w-20 and max-w-20.

  • w-20 with this class, I’m setting a fixed width of 150px for the table cells
  • max-w-20 with the help of this class, I am ensuring the width does not exceed the value that I’ve set.