How to Get and Set CSS Variable Values with JavaScript

By  on  

CSS variables are a very welcome addition to the language, despite them being incredibly basic.  Sure we could use SASS or stylus but languages should never count on developers relying on frameworks and toolkits to accomplish what we know we need.  And just like every other part of a webpage, you can get and manipulate CSS variable values -- let's check out how!

Setting and Using a CSS Variables

The traditional method of using native CSS variables is adding it to root:

:root {
    --my-variable-name: #999999;
}

Simple.  Also remember that CSS variables are nowhere near as powerful as variables within SASS, stylus, etc.

Getting a CSS Variable's Value

To retrieve the value of a CSS variable within the window, you use getComputedStyle and getPropertyValue:

getComputedStyle(document.documentElement)
    .getPropertyValue('--my-variable-name'); // #999999

The computed variable value comes back as a string.

Setting a CSS Variable's Value

To set the value of a CSS variable using JavaScript, you use setProperty on documentElement's style property:

document.documentElement.style
    .setProperty('--my-variable-name', 'pink');

You'll immediately see the new value applied everywhere the variable is used.

I had anticipated the need for disgusting hacks to accomplish CSS variable manipulation with JavaScript so I'm happy it's as easy as described above!

Recent Features

Incredible Demos

  • By
    MooTools 1.2 OpenLinks Plugin

    I often incorporate tools into my customers' websites that allow them to have some control over the content on their website. When doing so, I offer some tips to my clients to help them keep their website in good shape. One of the tips...

  • By
    Create Spinning Rays with CSS3 Animations & JavaScript

    Thomas Fuchs, creator of script2 (scriptaculous' second iteration) and Zepto.js (mobile JavaScript framework), creates outstanding animated elements with JavaScript.  He's a legend in his own right, and for good reason:  his work has helped to inspire developers everywhere to drop Flash and opt...

Discussion

  1. Ben C

    This is great! I hadn’t heard about this feature before now.

    With regard to comparisons with variables in CSS pre-processor languages like SASS, correct me if I’m missing something, but that seems to overlook what is so useful about this new feature, which is that variable values can be manipulated at run-time in the browser, meaning you can take into account contextual data like viewport size or user input; this is of course not possible with SASS variables, whose values are fixed at compile time.

  2. Josep V.

    I’ve been for a few days using this API and its greats. The only thing that I don’t like is that if you set the vars in a Child, and then you want to get the variables in a SubChild, you won’t be able to fetch anything.

    On the other hand if you use it in your css or styles property, it will work… it’s a bit odd that cascading of vars works for the css, but not for the prototype of these elements. Thoughts?

    • Josep V.

      Oh the frameworks backfire sometimes! answering myself on the previous entry… custom properties won’t cascade to the element until they are added to the DOM which *completely* makes sense.

  3. Ciaran O'Kelly

    Here’s a function to help:

    function cssVar(name,value){
        if(name[0]!='-') name = '--'+name //allow passing with or without --
        if(value) document.documentElement.style.setProperty(name, value)
        return getComputedStyle(document.documentElement).getPropertyValue(name);
    }
    
    
    //get a css var:
    cssVar('bgcolor') //returns #F60
    
    //set a css var:
    cssVar('bgcolor','red') //returns red
    
    • Harsh
      const cssVar = ( name, value ) => {
      
          if(name.substr(0, 2) !== "--") {
              name = "--" + name;
          }
      
          if(value) {
              document.documentElement.style.setProperty(name, value)
          }
      
          return getComputedStyle(document.documentElement).getPropertyValue(name);
      
      }
      
  4. James Schwartz

    This article is the perfect balance between concise and informative… I found this in a time of need and couldn’t be more satisfied, I wish I could share with the author some freshly poured orange juice, sadly this is not doable :(. know my gratitude, friend.

  5. Marcio

    Can you use another css variable as the value?

  6. Scott

    Clearly, a group of people were working with insufficient consumption of caffeinated liquids as this is not intuitive.

    You use

    document.documentElement.style.setProperty(name, value)
    

    To set the value!

    But contrary to intuition, you use:

    getComputedStyle(document.documentElement).getPropertyValue(name);
    

    to get the value; rather than:

    document.documentElement.style.getProperty(name);
    

    I don’t believe I’ve come across anything so completely different in any other DOM related JavaScript procedures. The set and the gets always seem to correspond with each other.

    Then again; in about six months I will have forgotten that I posted comment.

  7. # auto rotate with css var

    > demo

    https://codepen.io/xgqfrms/pen/JQVPzx

  8. Mohammad

    The only problem I can see with this is refactoring.
    If I renamed the variables in CSS, my JS code will be broken and vice versa. You should always remember to change the variable name in JS and CSS.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!