Why you should (probably) use CSS truncation instead of a JS truncation library

There are a few reasons you'd want to truncate a sentence, but the one I've run into most commonly is as a solution to "can you fit this copy into this area on a design"?

For this use case, I've seen engineers reach for 2 tools in the toolbox, either a JavaScript truncation library, or CSS. There is a time and a place for JavaScript truncation, but CSS can usually do all you want, and more!

Let's take two sentences that have the same number of characters.

  • Lila loves lilies and lilacs
  • Wow wiggly wombat wednesdays

These are contrived examples based on the fact that in a common sans-serif font like Arial, lowercase L's and I's tend to be the skinniest, (followed closely by j, f, t, and f), and W's and M's are the widest. Sentences do vary quite a bit, but if I'm trying to test extremes I'll use a series of L's or W's.

In this example, we want to limit these sentences to be a single line that truncates at 180px.

If we use character truncation with 25 characters, the first sentence fits with room to spare, but "wiggly wombats" is too long :(

CSS can handle this with no problem though!

All you need for the CSS is to use three lines

overflow: hidden;

text-overflow: ellipsis;

white-space: nowrap;

Bonus reasons to use CSS include:

  • Screenreaders can read the entire thing
  • You don't have to include another dependency in your JS chain, which both improves performance and reduces ongoing maintenance.
  • JS is more likely to cause a flash of unstyled text (if it takes longer to load JS than CSS and you load them separately, the complete sentence might show briefly before it gets truncated)

There is a time and a place for character-based truncation, but I'd start with CSS.

Code Sandbox