Languages
[Edit]
EN

CSS - set CSS variable using JavaScript

3 points
Created by:
Majid-Hajibaba
972

In this article, we would like to show you how to set CSS variable using JavaScript.

Quick solution:

var root = document.querySelector(':root');  // gets root element

function setVariable(name, value) {
    root.style.setProperty(name, value);
}


// Usage example:

setVariable('--variable-name', 'variable-value');

 

Practical example

In this example, we set --primary-color variable with orange value, then we use it as a background for a div element with .primary class.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div.primary {
        background: var(--primary-color);
    }

  </style>
</head>
<body>
  <script>

    var root = document.querySelector(':root');  // gets root element

    function setVariable(name, value) {
        root.style.setProperty(name, value);
    }


    // Usage example:

    setVariable('--primary-color', 'orange');  // sets --primary-color with orange value

  </script>
  <div class="primary">This div background color uses --primary-color variable that has been set using JavaScript</div>
</body>
</html>

 

See also

  1. CSS - declaring global CSS variables

  2. CSS - get existing CSS variable value

References

  1. :root - CSS: Cascading Style Sheets | MDN
  2. Using CSS custom properties (variables) | MDN

Alternative titles

  1. CSS - set global variable from :root using JavaScript
  2. CSS - set CSS variable from script tag using JavaScript
  3. CSS - create CSS variable using JavaScript
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join