The CSS calc() function
The CSS calc() function does math right inside a value, and its superpower is mixing units that otherwise cannot be combined — like calc(100% - 80px). Use it for widths, spacing and sizes that depend on two different reference points. One gotcha: the + and - operators must have a space on each side.
Overview
calc() lets you do arithmetic inside a CSS value. Its headline feature is the one thing plain CSS cannot do: mix units. 100% - 80px combines a relative unit and an absolute one, which is impossible with a static value but exactly what calc() is for — think a fluid column that needs to leave room for a fixed-width sidebar.
It supports the four basic operators: +, -, * and /. There is one rule that trips everyone up at least once: the + and - operators must have whitespace around them. calc(100%-80px) silently fails; calc(100% - 80px) works. The reason is that -80px is a valid number, so the parser needs the spaces to tell subtraction from a negative value.
It composes beautifully with everything else. You can nest it, and you can read a custom property inside it — calc(var(--gap) * 2) — which is how design systems build spacing scales from a single token.
Syntax
selector {
/* spaces required around + and - */
width: calc(100% - 2rem);
padding: calc(var(--gap) * 2);
}
Example
<style>
.bar {
width: calc(100% - 60px);
margin: 0 auto;
background: #1c7ce9;
color: #fff;
padding: 14px;
border-radius: 8px;
text-align: center;
font: 600 14px system-ui, sans-serif;
}
</style>
<div class="bar">width: calc(100% - 60px) — full width minus a fixed 60px</div>
Best practices
- Always put a space on each side of
+and-—calc(100%-2rem)fails,calc(100% - 2rem)works. - Reach for it when you genuinely need to mix units; for a single static value, a plain number is clearer.
- Combine it with var() to build spacing and sizing from design tokens, e.g.
calc(var(--gap) * 2). - You can nest
calc()and use it almost anywhere a length, number or percentage is accepted.
Frequently asked questions
How do I subtract a fixed amount from a percentage in CSS?
calc(), e.g. width: calc(100% - 80px). It is the only way to combine a percentage and a pixel value in one calculation.Why is my calc() not working?
+ or -. Write calc(100% - 20px), not calc(100%-20px).Can calc() mix different units?
Can I use calc() with CSS variables?
calc(var(--gap) * 2).