Files
30-seconds-of-code/snippets/truncate-text.md
Angelos Chalaris a8818b1998 Add extractor and builder
Tested and working
2019-08-22 14:04:18 +03:00

927 B

title, tags
title tags
Truncate text layout,intermediate

If the text is longer than one line, it will be truncated and end with an ellipsis .

<p class="truncate-text">If I exceed one line's width, I will be truncated.</p>
.truncate-text {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  width: 200px;
}

Explanation

  1. overflow: hidden prevents the text from overflowing its dimensions (for a block, 100% width and auto height).
  2. white-space: nowrap prevents the text from exceeding one line in height.
  3. text-overflow: ellipsis makes it so that if the text exceeds its dimensions, it will end with an ellipsis.
  4. width: 200px; ensures the element has a dimension, to know when to get ellipsis

Browser support

⚠️ Only works for single line elements.