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

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
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.
</div>

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 and web site design. His expertise is WordPress & Magento as well as many other frameworks. Would you like to work with Nathan? Send him an email on [email protected]

It’s good to share

Join the discussion