The CSS calc() function
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.