Search code examples
javascripthtmlcsscss-variablescssom

How can I create CSS variables with JavaScript?


I'm using :root to create some CSS variables. Is it possible to create them with JavaScript instead of CSS? Below is a simple example:

<div id="container"></div>
:root {
  --first-color: #000;
  --second-color: #666666;
}

#container {
  background-color: var(--second-color);
  width: 90px;
  height: 90px;
}

Solution

  • Yes, you can do it via .setProperty() method:

    const root = document.documentElement;
    root.style.setProperty('--first-color', 'red');
    root.style.setProperty('--second-color', 'blue');
    p {
      color: var(--first-color);
    }
    
    div {
      color: var(--second-color);
    }
    <p>First color</p>
    <div>Second color</div>