calc() for Dynamic Values
You'll learn how to use CSS's calc() function to perform mathematical calculations with mixed units, creating flexible layouts that adapt to different screen sizes.
What Is calc()?
The calc() function lets you perform arithmetic (addition, subtraction, multiplication, division) directly in your CSS values. The real power? You can mix different units in a single calculation. Want a width that's 100% minus 50 pixels? calc() makes it possible.
Think of calc() as a mini calculator built into CSS. Just like you might calculate "total bill minus tip" in real life, calc() lets you say "full width minus sidebar width."
Core Syntax
.container {
width: calc(100% - 80px);
padding: calc(1rem + 2px);
font-size: calc(16px + 0.5vw);
}
You must include spaces around + and - operators (multiplication * and division / don't require spaces, but it's good practice).
Practical Applications
Responsive spacing:
.header {
height: calc(10vh + 2rem);
margin-bottom: calc(var(--base-spacing) * 2);
}
Layout calculations:
.sidebar {
width: calc(25% - 1rem);
}
Notice how calc() works seamlessly with custom properties and viewport units you've already learned.
Why This Matters
Without calc(), achieving precise "full-width-minus-fixed-value" layouts required JavaScript or awkward workarounds. Now your CSS can handle dynamic calculations that respond to viewport changes, custom property updates, and content flow—all in one declaration.
Key Takeaway: calc() performs mathematical operations with mixed units in CSS, enabling responsive designs that combine relative and absolute measurements in ways previously impossible.