Every now and then, my Clients want me to implement a card-based layout for a list of posts, reports or real estates. In this layout, each card has an image, heading and some text. This looks perfect on the designs, where the text is the same size on all cards. However, when the real content comes in, usually the design gets broken and each card has a different size. In this web dev idea I will show you how to limit the number of lines with CSS only!
Youtube Video – Limit the Number of Lines with CSS only
Demo and code (tl;dr)
See the Pen Untitled by Artur Karczmarczyk (@arturkarczmarczyk) on CodePen.
How to Limit Number of Lines in Block with CSS?
Let’s start by creating an HTML file with cards:
You will need some images to put in the cards. For that, you can use some free service, like pixabay.com or pexels.com. You can also use Envato Elements, which is a subscription-based platform offering millions of stock photos, graphics, videos at a single monthly subscription fee:
Base Styling for Card-Based Layout
Once the HTML is ready and some images for cards are in place, we can start styling. Here is my basic idea how the styling of cards for card-based layout can be achieved:
Use line-clamp
CSS Property to Limit Lines of Text in a Paragraph
Once the HTML is ready and the basic styling is in place, we can do our magic! We can use CSS line-clamp property. It would be amazing if we could just type:
However, the line-clamp
property is not supported yet. Instead we need to use a prefixed version: -webkit-line-clamp. You can find all details on it here. The -webkit-line-clamp property works only when the display is set to -webkit-box or -webkit-inline-box and the -webkit-box-orient is set to vertical. Let’s try!
The results are not satisfactory yet:
You can notice, that the card boxes are the same size now, however the text is overflowing them. That’s simple to solve, just use the hidden value of the CSS overflow property:
Finally, our cards look exactly as we wanted!
Summary
In this web dev idea I showed you how you can easily limit the lines in paragraph or block with CSS line-clamp property. I hope that this idea will let you create card-based layouts easily.
I encourage you to check out the Youtube video of this limiting number of lines web dev idea!
If you’d like to learn more on HTML, CSS and LESS in a structured, no-nonsense, hands-on manner, try my Udemy course!
Leave a Reply