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
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

Incredible Demos

  • By
    PHP / MooTools 1.2 Accordion Helper

    The MooTools Accordion plugin seems to be the plugin that people seem to have the most problems with. It's an awesome plugin, so I can see why so many people want to use it, but I think that may be part of the problem.

  • By
    Flexbox Equal Height Columns

    Flexbox was supposed to be the pot of gold at the long, long rainbow of insufficient CSS layout techniques.  And the only disappointment I've experienced with flexbox is that browser vendors took so long to implement it.  I can't also claim to have pushed flexbox's limits, but...

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!