Access CSS variable from javascript

Pablo picture Pablo · Jan 18, 2017 · Viewed 47.9k times · Source

Is there a way to access a css variable from javascript? Here my css variable declaration.

:root {
  --color-font-general: #336699;
}

Answer

Oriol picture Oriol · Jan 18, 2017

Just the standard way:

  1. Get the computed styles with getComputedStyle
  2. Use getPropertyValue to get the value of the desired property
getComputedStyle(element).getPropertyValue('--color-font-general');

Example:

var style = getComputedStyle(document.body)
console.log( style.getPropertyValue('--bar') ) // #336699
console.log( style.getPropertyValue('--baz') ) // calc(2px*2)
:root { --foo:#336699; --bar:var(--foo); --baz:calc(2px*2); }