6

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;
}
0

1 Answer 1

11

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Bless you. This was just the approach I needed for a problem I was having in Svelte.