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

  1. Use calc() anywhere a length, angle, or other numeric CSS value is accepted.
  2. Combine units like px, %, vw, rem, and vh.
  3. 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 - inside calc() to avoid parsing errors.
  • Nesting calc() is valid in modern browsers.
  • Use it inside custom properties for even more flexibility across your design system.