Get and Set CSS Variables with Javascript

Use-Cases of this Tutorial

  • Get the current value of a CSS variable in Javascript.
  • Set the value of CSS variable with Javascript.

Custom properties or variables is a very useful addition to CSS. In some case we may need to change the value of the CSS variable dynamically, or get the value of the variable in Javascript. This can be done using the native browser APIs.

Getting a CSS Variable's Value

:root {
    --bg-color: #336699;
}

#element {
	background-color: var(--bg-color);
}

To get the CSS variable's value in Javascript :

  • Use getComputedStyle() to get the real-time CSS properties of the element. CSS variables are applied on the root element of the document. This root element can be referred through document.documentElement
  • getComputedStyle() returns all CSS properties of the element. To get the value of a specific CSS property we need to use getPropertyValue() on it
var bg_color_val = getComputedStyle(document.documentElement).getPropertyValue('--bg-color');

// #336699
console.log(bg_color_val);

Setting a CSS Variable's Value

To get the CSS variable's value in Javascript :

  • First access the styles of the root element with document.documentElement.style
  • Then use setProperty to set the variable's value
document.documentElement.style.setProperty('--bg-color', '#999999');
Loading Comments