CSS Comparison functions: min(), max(), and clamp()
The min()
, max()
, and clamp()
functions, now supported in all modern browsers, are among the latest tools in making authoring websites and apps more dynamic and responsive.
1. CSS min( ) Function
The min() CSS function lets you set the smallest (most negative) value from a list of comma-separated values. It can take two parameters and a min function can be used inside another min function if the comparison is to be made between multiple values.
Syntax:
min(value1, value2);
min(value1, min(value2, min(value3, value4)));
2. CSS max( ) Function
The max() CSS function lets you set the largest (most positive) value from a list of comma-separated values. It is used to return the largest value from a set of comma-separated values. It can accept length, frequency, integer, angle, and time types of values.
Syntax:
max(value1, value2...);
3. CSS clamp( ) Function
The clamp() CSS function is used to clamp the value between an upper and lower bound. It takes three parameters which are listed below:
- Minimum value
- Preferred value
- Maximum value
The minimum value comes in handy when the preferred value is smaller than the minimum value similarly maximum value comes in handy when the preferred value is more than the maximum value. The preferred value becomes useful when it is between the minimum and maximum value.
Syntax:
clamp(Min, Pre, Max);
Example
How To Add Fallback For Non-Supporting Browsers
As with any new CSS feature, it’s important to provide a fallback. To achieve that, we can either use the one of the below:
1. Add Fallback Manually
It means that we should provide a fallback by adding the property before the CSS comparison one. See the example below:
.test {
padding: 4rem 1rem;
padding: clamp(2rem, 10vmax, 10rem) 1rem;
}
Supporting browsers will ignore the first one. While non-supporting ones will use the first padding.
2. Using CSS @supports
We can use @supports
feature query to detect if the CSS comparison functions are supported. Any browser that supports the comparison functions should have support for the @supports
feature query.
.test {
/* Default, for non-supporting browsers */
padding: 4rem 1rem;
}
@supports (width: min(10px, 5vw)) {
/* An enhancement for supporting browsers */
.test {
padding: clamp(2rem, 10vmax, 10rem) 1rem;
}
}
Browser compatibility
Reference
Thanks for reading.