Using CSS Line Clamp for excerpts

Cover Image for Using CSS Line Clamp for excerpts

At the beginning of the year, I was working on a client's website that had multiple sources of information presented as different custom post types. One issue we were facing was to adjust the post excerpts with the design.

A grid layout was being used for most of the posts display, and the ideal scenario was to make them look uniform in length, including the excerpt. Since this information is dynamic and we won't be able to predict the length in every case, we opted to find a solution using CSS.

While testing different options, we came across the line clamp property. It essentially truncates text at a specific number of lines. Let's say we want all our excerpts to be limited to 3 lines maximum. We can use CSS line clamp for that. According to Can I use?, the line clamp property has a 97.7% global percentage across browsers. As of the time of writing this, it is not available for IE 11 and Opera Mini.

This property solved our issue and the end result looked incredible. We limited the lines to 2 and that worked perfectly with the layout we were using.

Testing with my personal blog

With my personal blog, I was having the same issue with having various line lengths depending on the post and excerpt. I had some posts with 6 lines vs. posts with 3. Visually, I didn't like how it looked, so I decided to use the same line clamp property and limit the lines to 3.

Here's the before and after:

Screenshot - Before / After CSS Line Clamp

Usage

Here's the code you would need to apply to the element you want to limit the lines on:

.entry-content {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

In my case, with my Wordpress blog, I applied it to the .entry-content CSS class which displays the post excerpt.

CSS Line Clamp example