The clamp() function defines a minimum value, a preferred value, and a maximum value.
A quick recap of min() and max() before we talk about clamp():
We can use the min() function to define a maximum value for a property. It's the maximum value we define because in the list of provided parameters, min() will always pick the smallest value. For example, width: min(700px, 90%) is always 700px or less, which means that the maximum width is 700px.
div {
width: min(90%, 700px);
}
We can use the max() function to define a minimum value for a property. It's the minimum value we define because in the list of provided parameters, max() will always pick the largest value. For example, width: max(300px, 90%) is always 300px or more, which means that the minimum width is 300px.
div {
width: max(300px, 90%);
}
If we want to define a default value and both a minimum and maximum value, we could do this:
div {
width: max(300px, min(90%, 700px));
}
The max() function picks the largest value, either 300px or the result of the min() function if it's larger than 300px. This defines the minimum width. The min() function picks the lowest value, either 700px or 90% if it's less than 700px. This the defines the maximum width with 90% as the default value.
Since nesting functions is super complicated and my brain still hurts from writing this paragraph, there's a handy alternative for this, clamp().
clamp() takes three parameters, a minimum value, a preferred value, and a maximum value.
div {
width: clamp(300px, 90%, 700px);
}
The width of the <div> is 90% with a minimum width of 300px and maximum width of 700px. It's basically a shorter way of writing:
div {
width: 90%;
min-width: 300px;
max-width: 700px;
}My blog doesn't support comments yet, but you can reply via blog@matuzo.at.





