CSS: Min, Max, and Clamp
When I’m writing CSS, sometimes the amount of properties I have on my classes starts to feel ridiculous. One way we can reduce the amount of code in our CSS files is by using the
These functions allow you to specify which value from a list of values is applied to a specific CSS property. This is helpful when you want the value to dynamically change. For example, if you want an element’s width, height, or font size to change in response to different window sizes. These functions are also valuable because they can handle the job of more than one property at once. Here is a basic example of min and max.
Min will set the width to the smallest of the values you pass in. The width of this element would be 50% of its parents’ width, until the parent grew larger than 600px. After that it would stay at the smaller 300px value.
Max will set the value to the larger of the values passed in. Here our element would stay at 300px until our window grew taller than 600px, at which point it would stay at the larger 50vh value.
To do this without min and max, we’d have to write this:
We’ve not only shortened our code, but also arguably made it easier to quickly understand as well.
Lastly, the clamp function is a combination of the two. Clamp takes three arguments: the min, the preferred middle value, and the max.
Here, the smallest the element can be is 300px, the largest is 500px, and if 50% of the parents’ width is between them, that’s your width. Turning 3 separate property declarations into one is pretty nice!
You can even do calculations inside the functions, without calling a
calc() function. Just add the math inline and it’s handled.
These functions may just be syntactic sugar, but since they make the code easier to write, parse, and understand while not overly obscuring what is truly going on, I’d say they’re the best kind of syntactic sugar.