Home  >  Q&A  >  body text

Get the calculated value of a CSS variable using a calc-like expression

In JavaScript, you can use getPropertyValue(property) to get the value of a CSS variable. This function is useful for retrieving variables declared in a :root block.

:root {
    --example-var: 50px;
}

However, if this variable expression contains a function like calc, the getPropertyValue call will return the expression as text rather than computing it, even with getCompulatedStyle# The same is true for ##.

:root {
    --example-var: calc(100px - 5px);
}

How to get the calculated value of a CSS variable using CSS functions such as calc?

See examples below:


let div = document.getElementById('example');
console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
:root {
  --example-var: calc(100px - 5px);
}
<div id='example'></div>


P粉111627787P粉111627787330 days ago930

reply all(2)I'll reply

  • P粉936509635

    P粉9365096352023-10-26 00:55:18

    A strange way is to add

    
    :root {
      --example-var: calc(100px - 5px);
    }
    
    #var-calculator {
        // can be fetched through .getBoundingClientRect().width
        width: var(--example-var); 
    
        // rest of these just to make sure this element
        // does not interfere with your page design.
        opacity: 0;
        position: fixed;
        z-index: -1000;
    }
    
    
    
     <custom-element>
      <div id="var-calculator"></div>
    </custom-element>
    
    
    const width = document.getElementById('var-calculator').getBoundingClientRect().width

    I don't know if this will work for your use case, but I just tested it and it works.

    reply
    1
  • P粉838563523

    P粉8385635232023-10-26 00:31:35

    Technically you can't, since the calculated value is not static and will depend on other properties. In this case it's simple since we're dealing with pixel values, but imagine a situation where you would have percentage values. The percentage is relative to other properties, so we can't calculate it before using it with var(). The logic is the same if we use units like em, ch etc.

    The following is a simple example to illustrate:

    let div = document.getElementById('example');
    console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
    console.log(window.getComputedStyle(div).getPropertyValue('font-size'))
    console.log(window.getComputedStyle(div).getPropertyValue('width'))
    console.log(window.getComputedStyle(div).getPropertyValue('background-size'));
    :root {
      --example-var: calc(100% + 5px - 10px);
    }
    #example {
      font-size:var(--example-var);
      width:var(--example-var);
      background-size:var(--example-var);
    }
    <div id='example'>some text</div>

    reply
    0
  • Cancelreply