CSS math functions enable the use of mathematical expressions for property values.
In this tutorial, you'll learn about the calc()
, max()
, and min()
functions.
The calc() Function
The calc()
function allows you to perform calculations to determine a property value.
Syntax
calc(expression)
Where expression
(required) is a mathematical expression whose result will be used as the property value.
Allowed Operators:
- + (Addition): Adds two values together.
- - (Subtraction): Subtracts one value from another.
- * (Multiplication): Multiplies two values together.
- / (Division): Divides one value by another.
Example:
Use calc()
to determine the width of a <div>
element.
#section {
width: calc(50% - 50px);
background-color: green;
}
In this example, suppose if the parent container has 400px width, the width of the #section
(div) element will be 150px (200px - 50px), as shown below.
The max() Function
The max()
function in CSS chooses the largest value from a list of comma-separated values to set as the property's value.
Syntax
max(value1, value2, value3,...)
Example:
Here's how you can use it to set the width of #section
element to the larger of 40% or 200px:
#section {
background-color: green;
width: max(40%, 200px);
}
In this example, the parent container has 400px width. So, the lager of 40% (160px) or 200px is 200px. Hence, the width of the #section
(div) will be 200px, as shown below.
The min() Function
The min()
function in CSS selects the smallest value from a list of comma-separated values to set as the property's value.
Syntax
min(value1, value2, value3,...)
Example:
Here's how you can use it to set the width of #section
(div) to the smaller of 40% or 200px:
#section {
background-color: green;
width: min(40%, 200px);
}
In this example, the parent container has 400px width. So, the smaller of 40% or 200px is 40% (160px). Hence, the width of the #section
(div) will be 160px (40%), as shown below.