CSS calc() · Astro Tech Blog

calc()

The calc() function lets you perform mathematical operations right inside CSS:

Demo: calc() Examples
HTML
<div class="calc-demo">100% - 40px</div>
<div class="calc-demo2">50% + 20px</div>
<div class="calc-demo3">(100% / 3) - 10px</div>
CSS
div { background: #6366f1; color: white; padding: 8px 16px; margin: 4px 0; border-radius: 6px; }
.calc-demo { width: calc(100% - 40px); }
.calc-demo2 { width: calc(50% + 20px); }
.calc-demo3 { width: calc((100% / 3) - 10px); }
Live Output Window

Supported Operators

OperatorExample
+calc(100% + 20px)
-calc(100% - 40px)
*calc(2 * 20px)
/calc(100% / 3)

Spacing Rule

Spaces are required around + and - operators but optional for * and /:

/* Correct */
width: calc(100% - 40px);

/* Incorrect — will not work */
width: calc(100%-40px);

Mixing Units

calc() is especially useful when mixing different unit types:

Demo: Practical calc()
HTML
<div class="card">
<p>This card uses calc() for responsive sizing</p>
</div>
CSS
.card {
background: linear-gradient(135deg, #6366f1, #8b5cf6);
color: white;
padding: 1rem;
border-radius: 8px;
width: calc(100% - 2rem);
max-width: calc(600px - 2rem);
font-size: calc(0.875rem + 0.5vw);
margin: 0 auto;
}
Live Output Window