简体   繁体   中英

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: --second-color;
  width: 90px;
  height: 90px;
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM