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?
let div = document.getElementById('example'); console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
:root { --example-var: calc(100px - 5px); }
<div id='example'></div>
A strange way is to add
I 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
,ch
etc.The following is a simple example to illustrate: