- Web Developer
- Posts
- Modern CSS - Math Functions: calc(), min(), max(), clamp()
Modern CSS - Math Functions: calc(), min(), max(), clamp()
Exploring Modern CSS Mathematical Functions: calc, min, max, and clamp
In modern web development, achieving responsive and fluid layouts has become essential. Modern CSS offers strong support for mathematical functions like calc()
, min()
, max()
, and clamp()
, allowing you to dynamically adjust values based on different conditions.
calc()
Purpose: Perform basic mathematical operations, allowing for calculations between different units (e.g., rem to px).
The benefit of using calc()
is that you can dynamically calculate final values based on percentages, vh, or vw units according to the user's viewport size. For example:
div {
width: calc(100% - 20px);
}
div {
width: calc(100vw - 40px);
}
Additionally, calc()
can be used for color adjustments, especially in conjunction with HSL (Hue, Saturation, Lightness) color models to quickly create a palette of similar colors.
:root {
--base-hue: 210;
--base-saturation: 50%;
--base-lightness: 60%;
}
.color1 {
background-color: hsl(
var(--base-hue),
var(--base-saturation),
var(--base-lightness)
);
}
.color2 {
background-color: hsl(
calc(var(--base-hue) + 15),
var(--base-saturation),
var(--base-lightness)
);
}
.color3 {
background-color: hsl(
var(--base-hue),
calc(var(--base-saturation) - 10%),
calc(var(--base-lightness) - 10%)
);
}
.color4 {
background-color: hsl(
calc(var(--base-hue) - 15),
var(--base-saturation),
var(--base-lightness)
);
}
Reply