Logo - Albert Walicki
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;

Browser Support

According to Can I Use line-clamp truncation is supported by all major browsers except IE11 and Opera Mini.

IE-11 Support

To support IE 11, we can use max-height instead of line-clamp.

.truncate {
  display: block;
  max-height: 3.6em;
  line-height: 1.8em;
}

The line-height is set to 1,8em and max-height to 3,6em. Max lines are calculated in this way: 3,6em divided by 1,8em equals 2 lines.

Codepen demo to play with:

See more solutions!

CSS

Extra space below image

One of the most common problems that almost every junior frontend developer has is extra space below the image. Let's learn how to fix it with CSS

HTML

How to create a tooltip in HTML and CSS?

A short tutorial on creating an HTML and CSS tooltip without a single line of javascript. All you need to know is data-atributes

Logo - Albert Walicki

Hello, I'm a frontend developer with over six years of experience, freelancer. I'm also a mentor for junior frontend developers. I wrote a book for Junior Frontend developers called Frontend Unicorn.

BlogGlassmorphismAurora UIShapes in CSSUnique css illustrations

Get in touch!

Have a question or need a project? Contact me!

© 2020-present Albert Walicki. All Rights Reserved

Policy