Skip to content

Instantly share code, notes, and snippets.

@amelieykw
Created April 6, 2018 15:13
Show Gist options
  • Save amelieykw/61df85fb69f8685670a3d8b35aae130a to your computer and use it in GitHub Desktop.
Save amelieykw/61df85fb69f8685670a3d8b35aae130a to your computer and use it in GitHub Desktop.
[Use CSS "text-overflow" to truncate long texts] #CSS #HTML #truncate_long_text #text-overflow

When using Rails to truncate strings, you may end up with strings that are still too long for their container or are not as long as they could be. You can get a prettier result using stylesheets.

The CSS property text-overflow: ellipsis has been around for quite a long time now but since Firefox did not support it for ages, you did not use it. Since Firefox 7 you can!

Note that this only works for single-line texts.

If you want to truncate tests across multiple lines, use a JavaScript solution like Superclamp. There is also -webkit-line-clamp which works only on Chrome.

Example

Consider this HTML and Sass for a box that is not wide enough for its content:

<div id="greetings">
  Hello universe!
</div>
#greetings
  width: 100px
  white-space: nowrap
  overflow: hidden
  text-overflow: ellipsis // This is where the magic happens

While incompatible browsers (IE 5.5, Firefox up until 6) will just cut off the text when it reaches its container's borders, in most browsers you will see something like:

Hello univ…

Nice, eh?

When you are doing this for a mobile application, also use -o-text-overflow to target Opera Mobile and Opera Mini which still use the prefixed version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment