calc() function inside another calc() in CSS

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.


Solution 1:

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.

Solution 2:

I'm one of the editors of the Values & Units spec, which defines calc().

calc() should be nestable inside of calc(). There was an oversight in the grammar/definitions for a while that technically didn't allow it, but I recently fixed that. Implementations haven't caught up yet, to my knowledge (tho it looks like Chrome 51 and Firefox 48 will have this fixed, woo!).

That said, there is zero reason to nest calc() expressions normally - they're exactly identical to just using parentheses. The only reason to do it at all is when using custom properties/variables.

Solution 3:

The reference you quoted is admittedly a bit confusing.

It is not possible to use a calc function inside another calc.

From the specs here: http://dev.w3.org/csswg/css-values/#calc-notation

...Components of a calc() expression can be literal values, attr() or calc() expressions, or values..

You can have calc expression inside the expressions, but not the calc() function itself.

And an example is given in that ref for nested expressions:

width: calc(100%/3 - 2*1em - 2*1px);

And also for multiple calc for multiple properties:

margin: calc(1rem - 2px) calc(1rem - 1px);

The syntax from the spec above:

The syntax of a calc() function is:

<calc()> = calc( <calc-sum> ) 
<calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* 
<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* 
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> ) 

Where a <dimension> is a dimension.

In addition, whitespace is required on both sides of the + and - operators. (The * and / operaters can be used without whitespace around them.)

UAs must support calc() expressions of at least 20 terms, where each NUMBER, DIMENSION, or PERCENTAGE is a term. If a calc() expression contains more than the supported number of terms, it must be treated as if it were invalid.

.