How can I create CSS variables with JavaScript? [duplicate]
Asked Answered
K

1

5

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;
}
Kwok answered 23/12, 2021 at 19:29 Comment(0)
L
10

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>
Lineal answered 23/12, 2021 at 19:34 Comment(1)
Bless you. This was just the approach I needed for a problem I was having in Svelte.Become

© 2022 - 2024 — McMap. All rights reserved.