CSS has several math functions that allow you to perform calculations on numeric values in your stylesheets. These functions can be particularly useful for creating responsive designs, where you need to make calculations based on the size of the viewport.
Here are some of the math functions in CSS:
- calc()
The calc() function allows you to perform mathematical operations on length values. It can be used to calculate the width, height, margin, padding, and other values of elements.
Example:
div {
width: calc(100% - 20px);
}
- min()
The min() function returns the smallest value from a set of comma-separated values.
Example:
div {
width: min(50%, 400px);
}
In this example, the width of the div will be set to 50% of the viewport width, or 400px, whichever is smaller.
- max()
The max() function returns the largest value from a set of comma-separated values.
Example:
div {
width: max(50%, 400px);
}
In this example, the width of the div will be set to 50% of the viewport width, or 400px, whichever is larger.
- clamp()
The clamp() function allows you to set a range of values based on the minimum and maximum values.
Example:
div {
width: clamp(200px, 50%, 800px);
}
In this example, the width of the div will be set to a value between 200px and 800px, with a preferred width of 50% of the viewport width.
- abs()
The abs() function returns the absolute value of a number.
Example:
div {
margin-top: abs(-20px);
}
In this example, the margin-top of the div will be set to 20px.
- round(), ceil(), and floor()
The round() function rounds a number to the nearest integer. The ceil() function rounds a number up to the nearest integer. The floor() function rounds a number down to the nearest integer.
Example:
div {
width: round(50.5px);
height: ceil(40.2px);
padding: floor(30.9px);
}
In this example, the width of the div will be set to 51px, the height will be set to 41px, and the padding will be set to 30px.