The what, how, and why of CSS clamp()
It’s Blogvent, day 4, where I blog daily in December!
CSS clamp() is cool and you should use it.
In a sentence, clamp() lets you assign a value to a CSS property between a minimum and a maximum range, and uses a preferred value in that range. It’s really helpful for responsive layouts and typography!
Syntax
clamp() has three parameters, in order:
- A minimum value
- A preferred value
- A maximum value
You can assign it to a property, like so:
.my-column {
width: clamp(200px, 40%, 400px);
}
The column width here is always between 200px and 400px wide, and defaults to 40% of its container width. If that 40% is less than 200px, the width will be 200px. Similarly, if that 40% is more than 400px, the width will be 400px.
Or, another example:
.my-special-text {
font-size: clamp(16px, 4vw, 24px);
}
The font size here is always between 16px and 24px, and defaults to 4% of the screen’s width. If a screen is 1000px wide, that means the font size would be 40px if it were that exact 4%, but with this function, it is capped at 24px.
Why would I use this over media queries?
It’s shorter! Honestly that’s why. You can accomplish a lot with a single line of clamp() (that is arguably easier to maintain) than a set of media queries. It reduces reliance on multiple rules and functions.
A typical media query approach for a column width might be:
.column {
width: 100%;
}
@media (min-width: 600px) {
.column {
width: 400px;
}
}
@media (min-width: 900px) {
.column {
width: 800px;
}
}
But with clamp(), you could do:
.column {
width: clamp(100%, 50vw, 800px);
}
This is way shorter, and I would argue, easier to read and maintain!
Resources
CSS clamp() is widely supported, so you can safely use it across your apps and websites.
If you’d like to learn more, here’s some handy links for ya:
Until next time!