Mastering CSS calc(): The Secret Weapon for Flexible Layouts

calc() is a CSS function that lets you perform basic arithmetic—addition, subtraction, multiplication, and division—on values to determine the final size, position, or spacing of an element. The beauty is that you can mix different units in the same expression, something that’s impossible with plain CSS values.

Instead of locking yourself to a fixed number or relying entirely on relative units, you can combine them.

For example:

Here, the element’s width is 100% of its container minus a 2rem margin.

Why It’s So Useful

The real power of calc() is flexibility. Let’s say you’re designing a fluid layout where some elements use percentages and others use absolute units like pixels or rems.

It’s especially handy when:

  • You need to leave space for fixed elements (like sidebars or headers) while keeping the rest fluid
Here, we combine relative spacing with a fixed offset so it looks consistent regardless of font size changes.
(click on the image to open in a new tab)
  • Typography and spacing need to scale, but still respect a base offset
This makes the heading scale smoothly with screen size, but still has a base size for readability.
(click on the image to open in a new tab)

  • Responsive designs require subtle size adjustments without rewriting your CSS at every breakpoint
Here, calc() lets you mix percentages and pixels so the content area shrinks or grows, but still respects the fixed sidebar space.
(click on the image to open in a new tab)

Things to Keep in Mind

calc() doesn’t break the cascade—it works just like any other CSS value.

NOTE: letting space around operators matters: calc(100% - 20px) works, calc(100%-20px) does not.

Although my blog doesn’t support comments, feel free to reply via email or X.