CSS provides several math functions to dynamically calculate values for various properties. These functions help in creating responsive and adaptable designs.
The following math functions are available in CSS:
calc()
: Performs calculations to determine CSS property values.min()
: Returns the smallest value from a set of values.max()
: Returns the largest value from a set of values.clamp()
: Sets a value within a defined range./* Example using calc() */
.example1 {
width: calc(50% - 20px);
height: calc(100px + 20px);
background-color: #FF5722;
}
/* Example using min() and max() */
.example2 {
width: min(300px, 50%);
height: max(100px, 10vw);
background-color: #3F51B5;
}
/* Example using clamp() */
.example3 {
width: clamp(150px, 30%, 300px);
height: clamp(100px, 20vw, 200px);
background-color: #9C27B0;
}
calc()
The box width is calculated as 50% of the container width minus 20px, and height is 100px plus 20px.
min()
and max()
The box width is the smaller value between 300px and 50% of the container width, and height is the larger value between 100px and 10% of the viewport width.
clamp()
The box width is clamped between 150px and 300px, with a preferred value of 30% of the container width. Height is clamped between 100px and 200px, with a preferred value of 20% of the viewport width.