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

  • By
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

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.

  9. Dale Landry

    What if you wanted to get a css variable that you did not know the name of? Maybe I have a set of fontfaces I want to query my CSS file for using JS, how could I get these?

    Example:

    :root {
      --fontface--Bitstream: "Bitstream Vera Serif Bold";
      --fontface--Roboto: "Roboto";
    }
    
    • getComputedStyle(document.documentElement)
          .getPropertyValue('--fontface--Bitstream');

      this returns …

      Bitstream Vera Serif Bold

  10. PD

    Thanks!!!

    This saved me a lot of ballache thanks to the good search indexing (DuckDuckGo) and well-written article that didn’t waffle on before getting to the critical matter at hand.

    Hugely valuable article.

  11. gman

    you can make variables

    .someclass {
      --foo: bar;
    }
    

    They aren’t root. How do set those?

    • They aren’t root. How do set those?

      you can target any element:

      Document.querySelector('.someclass').style.setProperty('--foo', 'bar');
      
  12. Theresa

    Hi I came across this and wondering if you can set the css

    :root {
      --var-color: "this is an advanced custom field color picker";
      
    }
    

    using this method? I have tried a lot of things but nothing seems to work so far.

  13. Tavis

    Thanks for putting this together David! I did not have success using

    getComputedStyle(document.documentElement)

    but

    getComputedStyle(document.body)

    does work as expected, so I just wanted to let you know in case browsers have changed the specification since this was originally published and you want to update it. Regardless, I really appreciate your contributions to the community, thank you again!

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