Loading lessons...
Math Functions: calc(), min(), max(), clamp()
Math Functions: calc(), min(), max(), clamp()
CSS can do MATH now! These four functions make fluid, flexible sizes easy.
calc()
Compute a value at runtime.
div {
width: calc(100% - 30px);
padding: calc(1rem + 2px);
}
Mix units freely! Always spaces around + and -.
min()
Take the SMALLEST of several values:
div {
width: min(100%, 500px); /* never wider than 500px, but shrink smaller */
}
max()
The LARGEST of several values:
div {
width: max(100px, 50vw); /* at least 100px, 50vw if bigger */
}
clamp()
The responsive magic: clamp(min, preferred, max).
p {
font-size: clamp(1rem, 2vw + 1rem, 2.5rem);
}
Font scales fluidly but is bounded at min and max!
Practical examples
/* full hero that stays within viewport size */
.hero {
min-height: min(80vh, 600px);
}
/* gutter-free mobile + bounded container */
.container {
width: min(100% - 2rem, 1200px);
margin-inline: auto;
}
TL;DR
calc() joins computed values. Beware spaces around +/-. min() picks smallest; max() picks largest; clamp() = min/preferred/max bound. Great for fluid type & responsive containers.