'use css vars from ancestors (with same var name) in css calc
I'd like to have a css var product value in a child element update based on the values of its ancestors.
E.g. is there a way to perform the following in pure css.
Or, whilst css preferred, what would be a good way to perform this via javascript. Perhaps with a setInterval function on the child element...
let el = document.getElementById('_3b0')
let product = 1;
while (true) {
let val = Number(getComputedStyle(el).getPropertyValue('--val'))
console.log(el.id,val)
product = product*val
el = el.parentNode
if (el.id == "container") break
}
document.getElementById('_3a0').style.setProperty('--product',product)
console.log('product:',product)
#_0 {--val : 1}
#_1 {--val : 2}
#_2 {--val : 3}
#_3a {--val : 3}
#_3b {--val : 4}
#_3a0 {--val:1; --product : calc( var(--val)/*product of all --vals from parents = 18 = 1 * 2 * 3 * 3 * 1*/ )}
#_3b0 {--val:1; --product : calc( var(--val) /*product of all --vals from parents = 24 = 1 * 2 * 3 * 4 * 1*/ )}
<div id="container">
<div id="_0">
<div id="_1">
<div id="_2">
<div id="_3a">
<div id="_3a0"></div>
</div>
<div id="_3b">
<div id="_3b0">
</div>
</div>
</div>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
