Truncating Text With CSS

Posted by Paul McMahon on 2012-10-05

Often you have text that you want to fit in a certain amount of space. For instance, with Doorkeeper, we want to truncate the title of the next event to fit nicely like the following.

One way to do this would be to truncate the title on the server side to a certain length, by using something like Ruby on Rails’ truncate method.

truncate(“Mobile Monday Tokyo - Oct. 22nd - At The Canadian Embassy”, length: 43)
# => "Mobile Monday Tokyo - Oct. 22nd - At The..."

This method can work if you are using a language in which all characters are the same width, but breaks down as soon as you have a language with characters of different width, such as Japanese.

truncate("『もう少し写真を上手に撮りたいWeb界隈の人のためのフォトワークショップ』- 第8回", length: 43)
# => "『もう少し写真を上手に撮りたいWeb界隈の人のためのフォトワークショップ』- 第8回"

The text wasn't even truncated despite looking almost twice the length! This is because the truncate method uses the number of characters, and some characters in Japanese take up twice the space as others.

Another problem with server side truncating is that it doesn’t allow for responsive design, where you want to dynamically adjust the width of the text based on the browser side.

Luckily, there is a better way to do this by adding the following CSS to the element we want to truncate:

white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

This works like the following:

Step 1: The base element

Step 2: Add white-space: nowrap

Step 3: Add overflow: hidden

Step 4: Add text-overflow: ellipsis

Using this method, the truncation is based on the space the text takes up, instead of the number of characters in the string, so it is always perfectly truncated to fill up the space.


But can I use this with Internet Explorer? Yes! The text overflow property has worked since IE6!

About the author


Paul is originally from Vancouver, Canada. He came to Japan in 2006 on the working holiday programme, wanting to experience a new and different culture. There he discovered the programming language Ruby, and the wonderful community that surrounds it. He's now a proud member of the community, organizing Tokyo Rubyist Meetup. He can be frequently found at entrepreneurial and technical events in Tokyo. In July 2013 he co-founded Doorkeeper KK to work and run the Doorkeeper service.

Skype Linkedin github
Email Skype Google Twitter Facebook Linkedin github
comments powered by Disqus