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:
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.
Multi-line Ellipsis
To achieve ellipsis for multiple lines, we can use:
-webkit-line-clamp
specify number of text lines before it stop breaking.
⚠️ Property won't work on its own, and also require: -webkit-line-clamp: <integer>
and display: -webkit-box
.
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:
<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:
<div className='whitespace-nowrap overflow-hidden text-ellipsis [direction:rtl]'>
<span lang='en'>‎{'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'}‎</span>
</div>
- Multiple lines:
<div className='line-clamp-2 max-w-[120px]'>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>