As of 2016, CSS Variables are fully usable in Chrome and Firefox, and IE has declared their intention to implement it as well.

Like many of the new JavaScript and CSS features, it can be a little hard to visualize what you might need or use a CSS variable for. For most of us, all of our experience in the pre-variable world, so it’s not necessarily obvious what we can use them for. We found one great answer though, communicating between JavaScript and CSS.

What Are CSS Variables?

CSS Variables (spec) adds two new concepts to CSS. You can now define custom properties which begin with two hyphens ( -- ):

html { --main-color: #06c }

You can then use them with var() :

a { color: var(--main-color) }

To anyone familiar with SASS or a similar language which compiles to CSS, the advantage of this is obvious, you can easily change colors, sizes, etc. in a single location.

Interestingly, variables follow the same inheritance rules of other CSS properties. For example, perhaps we want to tweak the main color on our blog:

.blog-post { --main-color: #9b806b }

Any links within the blog post portion of that page will now be a pretty terrible shade of brown.

Combining CSS variables with calc() expressions is just plain awesome:

html { --header-height: 40px } .page-content { top: calc(var(--header-height) + 10px) }

CSS Variables and JavaScript

We recently came across Lea Verou’s slider polyfill which expresses an interesting use of CSS Variables to communicate between JavaScript and CSS.

Historically, if you wanted to control CSS with a variable or function in JavaScript, your only option was to essentially write the CSS in JavaScript:

myElement.style.height = height + 'px'

It’s not uncommon to give up on seperate CSS all together and just write the styles in JS:

var newStyles = document.createElement('style') document.head.append(newStyles) newStyles.innerHTML = ".my-element {" + "height: " + height + "px;" + "width: 40px;" + "color: #9b806b;" + "}"

CSS Variables let us do something much better, taking the previous example:

.my-element { height: var(--element-height); width: 40px; color: #9b806b; }

Then, in JavaScript, we can write that variable out onto our element:

myElement.style.setProperty('--element-height', height + 'px')

If you really want to get clever, you can avoid the concatenation:

.my-element { height: calc(var(--element-height) * 1px); }

myElement.style.setProperty('--element-height', height)

We can even define a default in our CSS which will then be overridden by the JavaScript:

html { /* Will be overridden by JS */ --element-height: 20px }

We can now communicate cleanly between JavaScript and stylesheets. How awesome is that!

Here is a complete example for you to play with:

See the Pen Example of Using JavaScript to Set CSS Variables by Zack Bloom (@zackbloom) on CodePen.