π What is line-clamp?
line-clamp is a CSS property used to truncate text after a specific number of lines, adding an ellipsis (β¦) automatically. Itβs perfect for cards, blog previews, product descriptions, and anywhere you want clean text snippets without JavaScript.
Note
β Works with block-level or flex items
β No JavaScript required
π― Why Use line-clamp?
- Prevent text overflow in cards and components
- Keep UI layouts consistent across variable content
- Automatically apply ellipsis after N lines
- Improve readability and aesthetics
π― Syntax
line-clamp Syntax
line-clamp: <number-of-lines>;You typically combine it with:
- display: -webkit-box;
- -webkit-box-orient: vertical;
- overflow: hidden;
Modern CSS now supports line-clamp without vendor prefixes in many browsers, but this structure ensures maximum compatibility.
π§ͺ Example 1 β Clamp to 2 Lines
Two-line Clamp
.text {
line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
}π§ͺ Example 2 β Clamp to 3 Lines
Three-line Clamp
.description {
line-clamp: 3;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
}π§ͺ Example 3 β Responsive line-clamp
Responsive Clamp
.card-text {
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
line-clamp: 2;
}
@media (min-width: 768px) {
.card-text {
line-clamp: 4;
}
}On small screens β 2 lines
On large screens β 4 lines
π How It Works Internally
- Text is displayed normally until it reaches the specified line count
- Anything beyond that is clipped
- Ellipsis (β¦) appears automatically (browser-generated)
- Requires overflow to be hidden
Note
π¨ Styling the Clamped Text
Styling Example
.title {
font-size: 1.4rem;
font-weight: 600;
line-clamp: 1;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
}Useful for product cards, blog titles, etc.
π§± Example β Clamping with Hover Expansion
Hover to Expand
.preview {
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
line-clamp: 2;
transition: 0.3s;
}
.preview:hover {
line-clamp: unset;
}Hover removes the clamp β useful in dashboards.
β οΈ Common Mistakes
- β Forgetting display: -webkit-box; (clamping won't work)
- β Using line-clamp on inline elements (needs block or flex)
- β Not setting -webkit-box-orient (required for vertical clamping)
- β Expecting text to fade out β it clips with ellipsis instead
Note
π₯ Summary
line-clamp is a powerful and elegant tool for controlling text overflow in modern UI design. It makes multi-line truncation effortless, responsive, and visually clean, without relying on JavaScript.
Learn more βMDN Docs π