DEV Community

Arhan Khan
Arhan Khan

Posted on

CSS Variables in JavaScript: Change Styles on the Fly

CSS variables — custom properties — let you store a value once and reuse it across your whole stylesheet. Change the variable, and every element using it updates instantly. That alone is useful. The real magic is that JavaScript can read and change those variables at runtime, which makes them perfect for themes, live settings and animations.

You define a variable with two dashes, usually on :root so it is available everywhere, and use it with var().

:root {
  --main-color: #10b981;
  --spacing: 16px;
}

button {
  background: var(--main-color);
  padding: var(--spacing);
}
Enter fullscreen mode Exit fullscreen mode

From JavaScript, getComputedStyle() reads a variable's current value, and setProperty() on an element's style changes it. Change it on document.documentElement and the whole page updates — no need to touch individual elements.

const root = document.documentElement;

// Read the current value
const color = getComputedStyle(root).getPropertyValue("--main-color");
console.log(color); // "#10b981"

// Change it — every button updates instantly
root.style.setProperty("--main-color", "#f59e0b");
Enter fullscreen mode Exit fullscreen mode

This is the cleanest way to build a dark mode toggle. Instead of swapping classes on dozens of elements, you swap a handful of variables, and the entire page follows.

const toggle = document.querySelector("#theme-toggle");
toggle.addEventListener("click", () => {
  const isDark = document.body.classList.toggle("dark");
  root.style.setProperty("--bg", isDark ? "#0d121f" : "#ffffff");
  root.style.setProperty("--text", isDark ? "#ffffff" : "#111111");
});
Enter fullscreen mode Exit fullscreen mode

A few things to remember: a variable only applies where it is defined — a variable set on a single element does not leak to the rest of the page. And var() accepts a fallback value, var(--main-color, blue), which is used when the variable is not defined anywhere.

CSS variables turn your stylesheet into something JavaScript can control with a single line. Use them for colours, spacing and font sizes, and features like theme switching become trivial instead of a rewrite.

Top comments (0)