In this tutorial, we are going to show you how you can limit text length to the number of lines you would like to use with 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 regardless of how many lines it contains.
Where is this useful? Well, we recently used this when we had 3 columns displaying news posts and the heights of the boxes were varying heights because of the length of the title. In fact, we actually use this same method on our blog page.
We hope this helps, happy coding everyone!
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!
Jana
Hi Jana,
Can you share a link to your page and I’ll be able to help you with that.