0

I'd like to get the evaluated output of a css calc that refers to vars from parent elements. For example, the example below should log 21 not NaN. Is there a way to do this?

let outer = document.getElementById('outer')
let inner = document.getElementById('inner')

outer.style.setProperty('--A',7)
inner.style.setProperty('--B',3)
inner.style.setProperty('--C','calc (var(--A) * var(--B))')

let a = Number(getComputedStyle(inner).getPropertyValue('--C'))

console.log(a)
//is there a way to log '21' as opposed to NaN?
<div id="outer">
  <div id="inner">
  </div>
 </div>
 
 
Lee
  • 29,398
  • 28
  • 117
  • 170
  • 1
    `getPropertyValue` returns `calc (7 * 3)` so you could write a function that performs this calculation and returns the result. Obviously the `Number` constructor doesn't know what to do with this string value which is why you are getting `NaN`. – D M Apr 06 '22 at 14:01
  • @DM true, thanks, but I am wondering if there is a way to get the evaluated result without having to re-lookup `--A` and `--B` – Lee Apr 06 '22 at 14:03
  • 1
    I don't think you have to look up `--A` or `--B`. Calling `getPropertyValue('--C')` already substitutes their values into the result it returns to you. Now, if `--A` or `--B` themselves had a `calc(...)` in them, then yes, you'd need to go compute them first with this approach. – D M Apr 06 '22 at 14:04
  • 1
    https://stackoverflow.com/questions/48903509/evaluate-css-calc-function-in-js might help – Zach Jensz Apr 06 '22 at 14:07
  • @DM agreed, though it'd probably be easier to get `--A` and `--B` than to split the `calc (7 * 3)` string. I do have the more complex case (where parent vars are calcs on their parent vars) too. So it would be far more convenient to get the evaluation directly. – Lee Apr 06 '22 at 14:08
  • 2
    This question should **really** help https://stackoverflow.com/questions/56229772/get-computed-value-of-css-variable-that-uses-an-expression-like-calc – Zach Jensz Apr 06 '22 at 14:16
  • @ZachJensz Yes, thanks, although I think I'm possibly after the `used value` as opposed to the `computed value`, according to the definitions here: https://developer.mozilla.org/en-US/docs/Web/CSS/used_value – Lee Apr 06 '22 at 14:20
  • It would appear that the short answer is *No* . Though I'm not 100% sure... – Lee Apr 06 '22 at 14:23
  • @atomh33ls Thing is the used value depends on what property it's applied to. For example on width or height or font size the meaning of the `%` unit can vary widely, and yes you're not using % but custom properties can include it so they must just have blanket rule that you don't get any computation of them – Zach Jensz Apr 06 '22 at 14:24
  • @ZachJensz thanks, fair point. But does the browser not have to perform the calc at the moment of displaying the element, giving some evaluation of the calc. I suppose a kind of snapshot function could exist, but doesn't appear to atm. – Lee Apr 06 '22 at 14:28

0 Answers0