javascriptcsscss-variables

Accessing CSS calculated variable through Javascript


When working with calc()ulated properties in CSS, is it possible to access their expanded (i.e., actually calculated) values through Javacsript?

For instance, consider the following CSS:

:root {
    --ratio: calc(16 / 9);
    --width: 100px;
    --height: calc(var(--width) / var(--ratio));
}

And Javascript:

const computedStyle = window.getComputedStyle(document.documentElement);
console.info(computedStyle.getPropertyValue('--height'));

One would expect to see 56px being printed; instead, the string "calc(var(--width) / var(--ratio))" is returned.

Even if you try applying it to some CSS class property and reading from the class declaration instead, it won't work:

.rectangle {
    height: var(--height);
}

Javascript:

const rectangleClassDeclaration = /* find it through document.styleSheets */
console.info(rectangleClassDeclaration.style.getPropertyValue('height'));

And the console shows "var(--height)".

So, is there a way to access the final, calculated value through Javascript?


Solution

  • One hack that I could think of is applying the value to some DOM element and then reading from it instead.

    CSS:

    .rectangle {
        height: var(--height);
    }
    

    HTML:

    <div class="rectangle"></div>
    

    Javascript:

    const rectangle = document.querySelector('.rectangle');
    const computedStyle = window.getComputedStyle(rectangle);
    console.info(computedStyle.getPropertyValue('height'));
    

    And then you would see 56px as the result. But this is kinda hacky, so it would be good to find out some way of accessing the variable's computed value directly. It works, anyway.

    See my CodePen with working code.