calc() function inside another calc() in CSS

Raghavendra Prasad picture Raghavendra Prasad · Dec 22, 2014 · Viewed 32.4k times · Source

How do I use a CSS calc function inside another CSS calc function? According to this post it is possible but there is no example of that.

Answer

Bhojendra Rauniyar picture Bhojendra Rauniyar · Dec 22, 2014

It is possible to use calc() inside another calc().

An example:

div{
  width: calc(100% - (1% + 30px));/* calc(1% + 30px) is nested inside calc()*/
}
div p{
  width: calc(100% - 30px);/*100% is total width of the div*/
}

Update on nested calc with css variables:

.foo {
  --widthA: 100px;
  --widthB: calc(var(--widthA) / 2);
  --widthC: calc(var(--widthB) / 2);
  width: var(--widthC);
}

After all variables are expanded, widthC's value will be calc( calc( 100px / 2) / 2), then when it's assigned to .foo's width property, all inner calc()s (no matter how deeply nested) will be flattened to just parentheses, so the width property's value will be eventually calc( ( 100px / 2) / 2), i.e. 25px. In short: a calc() inside of a calc() is identical to just parentheses.

So, the current spec as well proves this using parentheses inside calc() is nested calc.

Learn more about css variables here.