Dynamic CSS with `calc()` Function: Perform Calculations in Stylesheets
Learn how to use the CSS `calc()` function to perform calculations directly within your stylesheets. This tutorial shows you how to create dynamic and responsive designs by combining different units and performing arithmetic operations for precise styling.
Performing Calculations in CSS with `calc()`
Understanding the `calc()` Function
The CSS `calc()` function lets you perform calculations directly within your stylesheets. This is incredibly useful for creating dynamic and responsive designs. You can use `calc()` to calculate lengths, percentages, times, frequencies, and angles. The four basic arithmetic operations—addition (+), subtraction (-), multiplication (*), and division (/)—are supported. `calc()` allows for mixing different units (e.g., pixels and percentages) within the same calculation, making it highly flexible.
`calc()` Function Syntax
The syntax is straightforward:
calc(expression)
The `expression` is a mathematical expression that is evaluated by the browser. The result of the calculation is used as the value for the CSS property.
Important Notes on `calc()`
- Whitespace: The `+` and `-` operators must be surrounded by whitespace. For example, `calc(50% - 10px)` is correct, but `calc(50%-10px)` is invalid.
- Whitespace (Recommendation): While not strictly required, adding whitespace around `*` and `/` operators is recommended for improved readability.
- Nesting: You can nest `calc()` functions within each other for more complex calculations.
Examples of `calc()`
These examples show `calc()` in action. You'd need to include corresponding HTML elements to see this in a browser. The CSS would apply the `calc()` functions to properties like `width`, `height`, or `padding`.
Example 1: Simple Calculation (Same Units)
This example uses `calc()` to calculate width and height, subtracting values with the same units.
CSS Code
div {
width: calc(150% - 75%);
height: calc(350px - 75px);
}
Example 2: Mixed Units
This demonstrates using mixed units (percentages and ems) within the `calc()` function, providing flexibility in combining different measurement systems.
CSS Code
div {
width: calc(40% + 10em);
height: calc(350px + 75px);
padding-top: calc(10% - 10px);
padding-left: calc(10% + 10px);
}
Example 3: Nested `calc()`
This example demonstrates nesting `calc()` functions to create more complex expressions.
CSS Code
div {
width: calc(calc(40em / 3) * 2);
height: calc(350px + 75px);
}