The CSS calc() function is used to perform mathematical calculations directly in CSS. It allows you to calculate property values using arithmetic operators.
In this chapter, you will learn what the CSS calc() function is, its syntax, supported operators, important rules, and how to use it through practical examples.
The calc() function evaluates a mathematical expression and uses the result as the value of a CSS property. It allows developers to combine different units, such as percentages, pixels, em, rem, and viewport units, within a single calculation.
The calc() function is commonly used when fixed values and relative values need to work together. For example, you can subtract a fixed-width sidebar from a percentage-based layout or calculate spacing dynamically.
The following syntax is used to perform calculations in CSS.
calc(expression)
In this syntax:
The calc() function supports the following arithmetic operators.
| Operator | Description |
|---|---|
| + | Adds two values. |
| - | Subtracts one value from another. |
| * | Multiplies a value. |
| / | Divides a value. |
The calc() function can perform simple arithmetic using values with the same unit. This makes it easy to calculate widths, heights, margins, and other CSS properties without manually computing the result.
The following example demonstrates how to use the calc() function with subtraction to calculate the width and height of an element.
Explanation
In this example, the width is calculated using calc(150% - 75%), resulting in 75%. Similarly, the height is calculated using calc(350px - 75px), resulting in 275px. The calculated values are applied automatically by the browser.
One of the biggest advantages of the calc() function is its ability to combine different units within the same expression. This helps create flexible layouts that adapt to different screen sizes.
The following example demonstrates how to combine percentage, pixel, and em units using the calc() function.
Explanation
In this example, the calc() function combines different units such as %, px, and em. The browser calculates the final values for properties like width, padding-top, and padding-left, making the layout more responsive.
The calc() function can also be nested inside another calc() function. This is useful when a calculation depends on the result of another calculation.
The following example demonstrates how to nest one calc() function inside another.
Explanation
In this example, the inner calc() function first evaluates 40em / 3. The result is then multiplied by 2 using the outer calc() function to determine the final width of the element. Nested calculations help simplify complex mathematical expressions in CSS.
We request you to subscribe our newsletter for upcoming updates.