How To Limit Text To N Lines With Css?

How to limit text to n lines with CSS?
Sometimes, we have to trim text to limit the number of lines. There are a few ways to do it with pure CSS. Let's learn how to achieve that The easiest way to limit text to n lines is to use line-clamp.

N can be any positive number, but it will be two or three lines most of the time. On my blog, I'm using line-clamp in all post-type components to ensure that it will have the same height as siblings.

One-line truncation

To truncate only one line we can use:

.truncate {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

White-space and overflow will do the job, while text-overflow will add three dots at the end of the line.

than one line?

Multiple lines truncation

The easiest way is to use this snippet:

.truncate {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-line-clamp: 2; /* number of lines to show */
           line-clamp: 2;
   -webkit-box-orient: vertical;
}

We are using multiple CSS properties:

  • overflow: hidden;
  • text-overflow: ellipsis; - optional, it will add three dots at the end of the trimmed line
  • display: -webkit-box;
  • -webkit-line-clamp: 2; - here we can specify how many lines we want to show to the user
  • line-clamp: 2;
  • -webkit-box-orient: vertical;

Referance albertwalicki

Write a Associte Comment
Markdown Editor