DEV Community

Adriano Fernandes
Adriano Fernandes

Posted on

6

Truncate multiline text with CSS line-clamp property

Hello people,
This is my first post, so feedback and suggestions are welcome!

A few days ago I was working on a quote component where I needed to limit the amount of characters on each quote to the mobile version only.

The first thing that came to mind was using text-overflow: ellipsis;, but this property only limits the characters inline.

So after doing some research I found the line-clamp property. This property limits the contents of a block to the number of lines you define.

For example, I needed to limit each statement to 3 lines, so I used:

  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-wrap: break-word;
  text-overflow: ellipsis; /* It will end with ellipsis when text-overflow: ellipsis is included */
  position: relative;
  visibility: visible; /* this is a tricky to work correctly at IOS */
Enter fullscreen mode Exit fullscreen mode

I created a Sass Mixin that contain fallback for older browsers:

@mixin truncate-text($font-size: 16px, $line-height: 1.4, $lines-to-show: 3) {
  display: -webkit-box;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-wrap: break-word;
  text-overflow: ellipsis; /* It will end with ellipsis when text-overflow: ellipsis is included */
  position: relative;
  visibility: visible; /* this is a tricky to work correctly at IOS */

  // Fallback for browsers that not support line-clamp
  @supports not (-webkit-line-clamp: $lines-to-show) {
    display: block;
    max-height: $font-size * $line-height * $lines-to-show;
    line-height: $line-height;
  }
}
Enter fullscreen mode Exit fullscreen mode

See an example:

As it was a mobile-only solution, it was a great solution as support for this property in mobile browsers is over 90%.

See you next time :)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (2)

Collapse
 
dchaur profile image
dchaur

Hey,

Really good article, since there's an existent bug with the line-clamp prop (bugs.webkit.org/show_bug.cgi?id=45399) I wasn't sure how to do it, the visibility: visible; trick works awesome.

Thanks

Collapse
 
djadriano profile image
Adriano Fernandes

Thanks a lot, I'm happy that works awesome for you :)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post