Mixing percentages and pixels with CSS calc()
calc() is useful when a CSS value needs to combine units that cannot be written as one fixed number. A common example is a fluid width with a fixed gap removed.
For example:
.my-element {
width: calc(100% - 20px);
margin-inline: 10px;
}
Here the element fills its containing block while leaving room for 10 pixels on each side. CSS can calculate the result even though % and px are different units.
The spacing around operators matters
Addition and subtraction require whitespace around the operator. Without it, the expression may be invalid.
.my-other-element {
width: calc(33.333% - 10px);
}
This produces roughly one third of the containing block minus a fixed gap. Parentheses can group more involved expressions when you need them.
At the time this article was written, calc() already had broad browser support and did not normally need a vendor prefix. A plain fallback can still help if you support much older browsers:
.my-element {
width: 95%;
width: calc(100% - 20px);
}
I would not use calc() where a normal percentage, padding, or modern layout property is clearer. It is at its best when the relationship really is a calculation.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- Why 100vh Doesn’t Always Fit a Mobile Screen
Choose svh, lvh, dvh, or a flexible min-height when mobile browser controls make 100vh an awkward fit.
- Making Links Easy to Recognize
Make links recognisable with underlines, clear focus states, useful text, and behaviour that does not surprise the reader.
- When CSS Layout Order Stops Matching the HTML
Keep Grid and Flexbox layouts aligned with the HTML order so keyboard focus and screen reader reading do not jump around the page.