How to use CSS calc() for dynamic sizing
· Category: HTML & CSS
Short answer
calc() lets you perform calculations with mixed CSS units directly in your stylesheets, enabling fluid layouts that respond to both fixed and relative measurements.
Steps
- Use
calc()anywhere a length, angle, or other numeric CSS value is accepted. - Combine units like
px,%,vw,rem, andvh. - Wrap the operator and operands with correct spacing around
+and-.
Example
.sidebar {
width: calc(25% - 1rem);
}
.hero {
height: calc(100vh - 60px); /* minus fixed header */
}
.container {
padding: calc(var(--spacing) + 4px);
}
Tips
- Always put spaces around
+and-insidecalc()to avoid parsing errors. - Nesting
calc()is valid in modern browsers. - Use it inside custom properties for even more flexibility across your design system.