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
904

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

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

However, if this variable expression contains a function likecalc, thegetPropertyValuecall will return the expression as text rather than computing it, even withgetCompulatedStyle# 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 ascalc?

See examples below:


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


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; }
 
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 withvar(). The logic is the same if we use units likeem,chetc.

    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); }
    some text
      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!