CSS calc() Function
What you'll learn: How to mix different units and perform math directly in your CSS to create flexible, responsive layouts without hardcoding values.
What Is calc()?
The calc() function lets you perform mathematical calculations right inside CSS property values. Think of it as a mini calculator built into your stylesheet. The real power comes from mixing different units in a single calculation—something impossible with plain numbers.
Imagine you want an element to be the full width of its container minus a fixed sidebar. Instead of using JavaScript or guessing pixel values, you can write: width: calc(100% - 250px). CSS does the math for you, even as the percentage changes with screen size.
How It Works
You can use calc() with addition (+), subtraction (-), multiplication (*), and division (/). Spaces around + and - are required, but optional for * and /.
.container {
width: calc(100% - 50px); /* Mix percentage and pixels */
padding: calc(1rem + 10px); /* Combine relative and absolute */
font-size: calc(16px + 2vw); /* Fluid typography */
margin-left: calc(20px * 2); /* Simple multiplication */
height: calc(100vh - 3rem); /* Viewport minus header */
}
Why It Matters
Before calc(), developers often needed JavaScript or awkward workarounds to achieve dynamic spacing. Now you can create truly responsive designs that adapt mathematically to any context—subtracting a fixed header from viewport height, adding padding to percentage widths, or scaling values proportionally.
Key Takeaway: calc() lets you perform math with mixed units (px, %, rem, vw, etc.) directly in CSS, creating flexible values that respond to different screen sizes and contexts without JavaScript.