How do I recalculate a new value of a CSS variable (custom property) in a sub-element using calc()
to modify the value inherited from a parent element?
This doesn’t work:
div {
height: var(--foo);
border: 1px solid #f00;
}
.a {
--foo: 100px;
}
.b {
--foo: calc(var(--foo) - 25px);
}
<div class=a>
<div class=b>
foo box
</div>
</div>
The browser seems to completely unset the value of --foo
on .b
.
Using the inherit
keyword in the calc()
expression also doesn’t work.
2
Answers
you can’t directly modify the value of a CSS variable that is inherited from a parent element. However, you can achieve this by using a different approach: setting a new CSS variable specifically for the sub-element and use that variable to calculate the desired value.
Declare the custom property (variable) and then declare the height with the classes