Clipping text with 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 the editor’s draft of the CSS Basic User Interface Module Level 3 that can help improve the situation is text-overflow
.
By giving it a value of ellipsis
the browser will Render an ellipsis character (U+2026) to represent clipped text replacing however many characters are necessary for the ellipsis to fit
.
As an example, let’s say you have a list where each item needs to be on a single (narrow) line. The markup could look like this:
<ul>
<li>List item 1</li>
<li>List item 2 is longer. Too long, actually.</li>
<li>List item 3</li>
</ul>
You could then use the following CSS:
ul {
width:180px;
padding-left:0;
list-style:none;
}
li {
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
}
See the Clipping text with CSS3 text-overflow demo page for an example. For text-overflow
to have any effect, the element (or one of its ancestors) needs to have a width, the element needs to have overflow
set to some other value than visible
, and there has to be a line of text that is longer than the element is wide.
So which browsers handle this? Since text-overflow
has been around since at least 2003, it is rather well-supported. It works in Safari, Chrome, Opera, and even in Internet Explorer 7+. For some reason it has not been implemented at all in Firefox, which is a bit surprising. I can’t think of any other CSS property that is supported in all major browsers except for Firefox. The good thing is that the only thing that happens in browsers that don’t support text-overflow
is that the text will be clipped without an ellipsis indicating it. Not great, but maybe not a showstopper either, depending on the circumstances.
Update: Seems like this is being worked on and will be included in Firefox 6, due later this year. See Bug 312156 - implement text-overflow: ellipsis from CSS3 text for more info.
If you want to give users a chance of reading the clipped text, you could set overflow
to auto
instead of hidden
to make a scrollbar appear. When this happens, the spec says that browsers should let users scroll to show more content. This only seems to work in Opera and IE9.
Finally a word of caution—don’t go setting text-overflow:ellipsis
on elements without first considering if you should instead be making room for more text in your layout. I view text-overflow:ellipsis
as a last-resort solution that will at least give the user an indication of text being clipped. If at all possible, all text should be displayed instead.
- Previous post: Validate URL syntax with JavaScript
- Next post: iOS tip: how to zoom on web pages that have disabled user zoom