CSS Math Functions
CSS math functions allow mathematical expressions to be used as property values. This is incredibly useful for creating flexible and responsive designs.
The calc() Function
The calc() function lets you perform calculations with different units. For example, you can subtract a pixel value from a percentage width.
Example
css
#main {
width: calc(100% - 100px);
}The max() and min() Functions
The max() function uses the largest value from a comma-separated list of values. The min() function uses the smallest value.
Example
css
.element {
width: max(50%, 300px); /* Will be at least 300px wide */
font-size: min(2rem, 5vw); /* Font size will be the smaller of 2rem or 5% of viewport width */
}The clamp() Function
The clamp() function "clamps" a value between an upper and lower bound. It takes three arguments: a minimum value, a preferred value, and a maximum value.
Example: Fluid Typography
css
h1 {
/* Font size will be 5vw, but not smaller than 1.5rem or larger than 3rem */
font-size: clamp(1.5rem, 5vw, 3rem);
}Test Yourself with an Exercise
Which function lets you perform calculations with different units, like `100% - 80px`?