Helping you build a better website
(and other interesting web stuff)

Silva Web Designs - Blog

Limit text length to X lines using CSS

Is it possible to limit a text length to “X” amount of lines using CSS? The answer is yes.

There is a way, but it is webkit-only. However, when you combine this with line-height: X, and max-height: X*N, it will also work in other browsers, just without ellipses.

Let’s take the following HTML:-

<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam consectetur venenatis blandit. Praesent vehicula, libero non pretium vulputate, lacus arcu facilisis lectus, sed feugiat tellus nulla eu dolor. Nulla porta bibendum lectus quis euismod. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat.

If we want to limit this so it only shows the first two lines of text we can do so by using the following CSS:-

.text {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   line-height: 16px;     /* fallback */
   max-height: 32px;      /* fallback */
   -webkit-line-clamp: 2; /* number of lines to show */
   -webkit-box-orient: vertical;

And there you have it, the text will now only show 2 lines of text.

Where is this useful? I recently used this when I had 3 columns displaying news posts and the heights of the boxes were varying heights because of the length of the title.

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

2 thoughts on “Limit text length to X lines using CSS

  1. Hi Nathan,
    I found this very useful, but as I am not so much into CSS, I don’t know how to adapt your code to my needs. I would like to “not display” the title of my posts, the 3 first lines of the posts. How would the CSS look like in that case?

    Thanks a ton!

Join the discussion