Home > Web Front-end > CSS Tutorial > How to Correctly Modify CSS Variables Using JavaScript?

How to Correctly Modify CSS Variables Using JavaScript?

DDD
Release: 2024-12-12 13:33:09
Original
388 people have browsed it

How to Correctly Modify CSS Variables Using JavaScript?

How to Edit CSS Variables with JavaScript Using Style.setProperty

In CSS, variables allow you to define color themes and other settings once and use them throughout your project. To edit these variables dynamically with JavaScript, you must utilize the appropriate methods.

Incorrect Method:

In your code, you attempted to update the CSS variable using setAttribute. However, this method is invalid for editing CSS variables.

Correct Methods:

There are three correct methods to edit CSS variables with JavaScript:

  1. documentElement.style.cssText:

    • Syntax: documentElement.style.cssText = "--variable-name: new-value"
  2. documentElement.style.setProperty:

    • Syntax: documentElement.style.setProperty("--variable-name", "new-value")
  3. documentElement.setAttribute('style'):

    • Syntax: documentElement.setAttribute('style', "--variable-name: new-value")

Example:

To change the --main-background-color variable to red:

document.documentElement.style.cssText = "--main-background-color: red";
Copy after login

Demo:


  
    
  

  
    <script>
      function changeColor() {
        setTimeout(() => {
          document.documentElement.style.cssText = &quot;--main-background-color: red&quot;;
        }, 2000);
      }
    </script>
  
Copy after login

In this demo, the background color will change to red after 2 seconds of loading the page.

The above is the detailed content of How to Correctly Modify CSS Variables Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template