Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calc() function inside another calc() in CSS

Tags:

css

css-calc

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.

like image 457
Raghavendra Prasad Avatar asked Dec 22 '14 05:12

Raghavendra Prasad


People also ask

Can I use Calc inside Calc?

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

What does CALC () do in CSS?

calc() The calc() CSS function lets you perform calculations when specifying CSS property values. It can be used anywhere a <length> , <frequency> , <angle> , <time> , <percentage> , <number> , or <integer> is allowed.

Can I use Calc in padding?

A solution for you would be to use CSS calc, it has good browser support and fixes your issue in quite a simple manner. The only downside here is that it doesn't calculate the padding-top in % but you simply cannot calculate padding-top in % from the height of the element unless you use javascript.

Can I use Calc for margin CSS?

You can use calc() anywhere where you would use numeric values (e.g.: width, max-height, margin-left, …) Can I Use calc? Data on support for the calc feature across the major browsers from caniuse.com.


2 Answers

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.

like image 88
Bhojendra Rauniyar Avatar answered Oct 13 '22 03:10

Bhojendra Rauniyar


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.

like image 34
Xanthir Avatar answered Oct 13 '22 01:10

Xanthir