Clipping text with '…' using CSS3 text-overflow

When you need to display an unknown amount of text in a constrained space you may need to somehow hide text that doesn’t fit. One way is to use overflow:hidden to quite brutally hide it. Doing this works, and it works cross-browser, but it can be difficult for the user to realise that text has been hidden since there is no visual indication of it. A property from CSS3 that can help improve the situation is text-overflow.

via Clipping text with CSS3 text-overflow by 456 Berea Street

text-overflow is actually a pretty awesome CSS3 property. It does exactly what we try to do in programming languages all the time when we have titles that can be too long for their space and you need to add ‘…’ after an x amount of characters. But text-overflow does it in CSS. It works in Safari, Chrome, Opera, and even in Internet Explorer 7+, but it doesn’t work in Firefox until Firefox 6. (Firefox 6? Yes, Firefox 6 will be released somewhere in August). No worries, Firefox 6- will respect the overflow: hidden property and will just hide the rest of the text.

How does it work?

It is as easy as declaring text-overflow: ellipsis; on an element. Do not forget to declare a width, otherwise the browser does not know where to put in the ‘…’ .

If you have a list of news items, for example

[html]
<ul>
<li>Do you really know what you’re doing as an entrepreneur?</li>
<li>The four categories of NoSQL databases</li>
<li>In between startups</li>
</ul>[/html]

And the following CSS:

[css highlight=”7″]
ul {
width: 250px;
}
li {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}[/css]

It will look like this:

That’s pretty cool isn’t it? No more coding, no more changing the amount of characters when the width of the element changes, just add 2 extra lines of CSS and you’re done. Perfect! Why didn’t I know about this property before?

Leave a comment