DEV3 Technologies home

DEV3 Developer Forum

How do I truncate text to 2 or 3 lines with an ellipsis in CSS and Tailwind?

dev3 ·

text-overflow: ellipsis only works on one line. I want a card description limited to three lines with "...". What is the supported approach?

#css#tailwind#line-clamp#text

0

1 reply

dev3 · Accepted answer

Use line-clamp

The standard line-clamp property is still catching up, but the -webkit- prefixed version is supported in all current browsers (including Firefox and Safari) and is what Tailwind outputs:

.desc {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

Tailwind (built in since v3.3):

<p class="line-clamp-3">{{ long description }}</p>
<p class="line-clamp-none md:line-clamp-4">...</p>

In v4 arbitrary numbers work too: line-clamp-[5].

Single line

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

Tailwind: truncate. In flex children remember min-w-0 (see the flex overflow topic).

Show more / less toggle

Toggle the class, and detect whether clamping is active before showing the button:

const el = document.querySelector('.desc');
const isClamped = el.scrollHeight > el.clientHeight;
button.hidden = !isClamped;
button.onclick = () => {
  el.classList.toggle('line-clamp-3');
  button.textContent = el.classList.contains('line-clamp-3') ? 'Show more' : 'Show less';
};

Pitfalls

  • Padding on the clamped element can reveal extra lines below the cut; put padding on a wrapper.
  • Do not clamp content that matters for accessibility (prices, legal text). Screen readers still read the full text, but sighted users cannot, so provide a way to expand.
  • Clamping applies to the rendered line count, so changing font size or width changes how much text shows.
  • Set the full text in a title attribute only as a convenience, not as a substitute.
0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.