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
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

  • By
    Prevent Page Zooming in Mobile Browsers

    Ever since I got my iPhone, I've been more agreeable in going places that my fiancee wants to go. It's not because I have any interest in checking out women's shoes, looking at flowers, or that type of stuff -- it's because my iPhone lets...

  • By
    Using MooTools to Instruct Google Analytics to Track Outbound Links

    Google Analytics provides a wealth of information about who's coming to your website. One of the most important statistics the service provides is the referrer statistic -- you've gotta know who's sending people to your website, right? What about where you send others though?

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.

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