0
0
CssHow-ToBeginner · 3 min read

How to Use calc() in CSS for Dynamic Calculations

Use the calc() function in CSS to perform simple math operations like addition, subtraction, multiplication, and division directly in property values. It helps combine different units, such as percentages and pixels, for flexible layouts.
📐

Syntax

The calc() function lets you write math expressions inside CSS property values. You write calc(expression) where expression can use +, -, *, and / with numbers and units.

Spaces around operators are required for addition and subtraction.

css
property: calc(expression);

/* Examples: */
width: calc(100% - 50px);
padding: calc(1rem + 10px);
💻

Example

This example shows how to use calc() to set a box width that is the full container width minus 100 pixels. It demonstrates combining percentage and pixel units.

css
html, body {
  margin: 0;
  height: 100%;
}
.container {
  width: 400px;
  border: 2px solid #333;
  padding: 10px;
}
.box {
  width: calc(100% - 100px);
  height: 100px;
  background-color: #4CAF50;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}
Output
A green rectangular box inside a 400px wide container. The box width is 300px (400px container width minus 100px). The box has white centered text.
⚠️

Common Pitfalls

  • Always include spaces around + and - operators; otherwise, calc() won't work.
  • Do not use calc() inside transform properties; it is not supported there.
  • Multiplication and division do not require spaces but be careful with operator precedence.
  • Mixing units without calc() is not possible; calc() helps combine units like % and px.
css
/* Wrong: Missing spaces around + */
width: calc(100%-50px); /* Won't work */

/* Right: Spaces included */
width: calc(100% - 50px);
📊

Quick Reference

Remember these tips when using calc():

  • Use spaces around + and -.
  • You can mix units like px, %, em, rem.
  • Supports +, -, *, and /.
  • Works in most CSS properties that accept length or size values.

Key Takeaways

Use calc() to combine different units and do math in CSS property values.
Always put spaces around plus and minus operators inside calc().
calc() works well for responsive layouts needing dynamic sizes.
Multiplication and division inside calc() do not require spaces but use carefully.
Not all CSS properties support calc(), avoid using it in unsupported places like transform.