Reverse Ellipsis and Multi-Line Overflow CSS

blog main image

If you have a long text and want to truncate it nicely, we commonly use ellipsis (...), and it's quite easy to implement in CSS:

.truncated-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

But what if we want to reverse it - to display the ellipsis at the beginning? (...longtext)
Or have the ellipsis appear on a second line, or third, etc. - or even in reverse ellipsis for multiple lines?

Not an easy task. Previously 🏛 was solved by:

  • complex approaches (e.g., canvas to calculate the width of a text)
  • unstable hacks/workarounds like .slice(0, 100).reverse().concat('...').reverse().

However, if you know the trick, you can achieve this using pure CSS easily.

Reverse Ellipsis

To get reverse ellipsis effect we should use a combination of technics:

  • direction: rtl; – which will reverse the text direction, placing the ellipsis at the beginning.

However direction, won't work alone, and we need special symbol ‎ to prevent reversing punctuation in our text:

  • ‎{text}‎ at both the start and end.
  • lang='en'- in the attributes required - in case we will use not only English language.
const text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

export default function App() {
  return (
      <div className='reverse-ellipsis'>
          <span lang='en'>&lrm;{text}&lrm;</span>
      </div>
  )
}

Multi-line Ellipsis

To achieve ellipsis for multiple lines, we can use:

⚠️ Property won't work on its own, and also require: -webkit-line-clamp: <integer> and display: -webkit-box.

export default function App() {
    return (
      <div className='multiline-ellipsis'>
          <p>Lorem ipsum dolor sit amet,</p>
          <p>consectetur adipiscing elit.</p>
          <p>Nunc in hendrerit nisi.</p>
      </div>
    );
}

⚠️

Even though line-clamp: not available without -webkit prefix and marked as Limited availability on MDN.
It still has >96% browser support percentage - which makes it usable in most of the cases.

Tailwind Versions

  • Simple ellipsis at the end:
Copied!
<div className='whitespace-nowrap overflow-hidden text-ellipsis max-w-[120px]'>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
  • Reverse ellipsis at the beginning:
Copied!
<div className='whitespace-nowrap overflow-hidden text-ellipsis [direction:rtl]'>
    <span lang='en'>&lrm;{'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'}&lrm;</span>
</div>
  • Multiple lines:
Copied!
<div className='line-clamp-2 max-w-[120px]'>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>

css
tricks
tailwind