The calc() Function
The calc() function allows you to perform calculations to determine CSS property values. It is incredibly useful for mixing different units (e.g., percentages and pixels) that would otherwise be impossible to combine.
1. Syntax
property: calc(expression);
The expression can use standard arithmetic operators:
+(Addition)-(Subtraction)*(Multiplication)/(Division)
Important: You must put whitespace around the + and - operators.
calc(50% -8px)(Invalid)calc(50% - 8px)(Valid)
2. Mixing Units
The real power of calc() is mixing units.
/* A container that is 100% width minus a 20px margin on each side */
.container {
width: calc(100% - 40px);
margin: 0 auto;
}
3. Use Cases
Centering Elements
.centered {
position: absolute;
left: 50%;
top: 50%;
/* Move back by half of its own width/height */
margin-left: -150px;
margin-top: -100px;
width: 300px;
height: 200px;
}
/* With calc() */
.centered-calc {
position: absolute;
left: calc(50% - 150px);
top: calc(50% - 100px);
}
Responsive Typography
h1 {
font-size: calc(1.5rem + 2vw);
}