How to Get the Value of a CSS Variable Using JavaScript?

You can get the value of a CSS variable (aka CSS custom properties) via JavaScript in the following way:

  1. Get the computed styles with the getComputedStyle() method, and;
  2. Use the getPropertyValue() method to get the value of a CSS variable.

Please remember that if the variable value has a leading space, it is returned as is when trying to access the variable value. To get the value without the leading space you can either use trim(), or you could specify the variable value without a leading space.

Get the Value of a Global Scoped CSS Variable

Let's suppose we have the following global scoped CSS variable:

:root {
    --color-background: white;
}

To get the value of this variable from the root element, we can do the following:

const styles = getComputedStyle(document.documentElement);
const bgColor = styles.getPropertyValue('--color-background');

console.log(bgColor); // output: ' white'

console.log(bgColor.trim()); // output: 'white'

As mentioned before, since our CSS variable value has a leading space, it is returned as is when we try to access it via JavaScript. To get rid of it we can use trim() as shown above, or remove the leading space from the CSS variable value itself.

Get the Value of a Local Scoped CSS Variable

Let's suppose we have the following CSS variable that is declared in the global scope as well as in the local scope:

:root {
    --color-background: white;
}

#footer {
    --color-background: pink;
}

And we have the following markup:

<div id="body">
    <p>body</p>
</div>

<div id="footer">
    <p id="footer-child">footer</p>
</div>

To get the value of this variable from the #footer element, we can do the following:

const styles = getComputedStyle(document.getElementById('footer'));
const bgColor = styles.getPropertyValue('--color-background');

console.log(bgColor); // output: ' pink'

console.log(bgColor.trim()); // output: 'pink'

As you can see, the #footer element returns the local scoped value here. This will also be true for any child of the #footer element (as it inherits from the parent), for example:

const styles = getComputedStyle(document.getElementById('footer-child'));
const bgColor = styles.getPropertyValue('--color-background');

console.log(bgColor.trim()); // output: 'pink'

As mentioned before, since our CSS variable value has a leading space, it is returned as is when we try to access it via JavaScript. To get rid of it we can use trim() as shown above, or remove the leading space from the CSS variable value itself.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.