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?
let div = document.getElementById('example'); console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
:root { --example-var: calc(100px - 5px); }
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().widthI don't know if this will work for your use case, but I just tested it and it works.
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 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); }