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.
It is possible to use calc() inside another calc().
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With