CSS Clamp Guide
clamp()
is a CSS function that allows you to clamp a value between a minimum and maximum value. It is a great tool for spacing and typography and very underused in my opinion. If you're interested in the technical details, check out the deepdive, MDN docs and the W3C spec.
A short overview of the syntax:
clamp(minimum, preferred, maximum)
Lets take the following clamp as an example: clamp(1rem, 0.4rem + 3vw, 4rem)
. When resizing the viewport the clamped value will be at least 1 rem and at most 4 rem. Between viewport widths of 20 rem and 120 rem the value will be clamped (fluid) between 1 rem and 4 rem linearly.
To clamp or not to clamp?
There are a few things to consider when using clamp()
, first lets take a look at the drawbacks:
- Complexity & readability: It is quite hard to read and understand what the value will be at a given viewport width in an instant.
- Lack of granularity: For highly granular control over your layout and spacing you might want to use manually defined specific values & media queries.
- Potential performance impact: While the performance impact of using clamp is generally negligible, extremely complex layouts or a large number of elements with clamp values might lead to a slight decrease in performance, especially when resizing the viewport. Always consider performance implications when building for less powerful devices.
And the benefits:
- Fluidity: Clamp allows you to create fluid layouts and spacing that scale with the viewport width. This is especially useful for typography and spacing because there are no akward spots where the media query just doesn't quite fit.
- Less code: Using clamp can reduce the amount of code needed for creating responsive designs.
Real world example
Using
max-width
of 1200px. When scaling down the viewport there is no difference in margin from 1200px and down.Using
clamp
of 1200px. When scaling down the viewport there is a nice, fluid margin all the way down to the minimum viewport width.