Get the calculated value of a CSS variable using a calc-like expression
P粉111627787
P粉111627787 2023-10-25 09:39:36
0
2
1018

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粉111627787
P粉111627787

reply all(2)
P粉936509635

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.

P粉838563523

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!