File Under: CSS

CSS Variables: WebKit Brings the CSS Jackalope to Life

The mythical beast known as the CSS Variable is about to be released into the wild.

The WebKit team, which builds the browsing engine that powers both the Safari and Chrome web browsers, recently landed preliminary support for CSS Variables, which means variables will likely turn up soon in Chrome/Chromium and Safari nightly builds.

Variables used to be one of the most requested features for CSS, particularly from programmers accustomed to languages with variables. But, between then and now, CSS preprocessors like SASS and LESS have largely filled the role by offering variables (and more). Still SASS and LESS are not CSS, and do require compiling, so there may still be a place for variables in CSS.

There’s nowhere to actually test out CSS variables yet, but you can read up on the proposed variable syntax at the W3C. The spec is currently a working draft and may change considerably before it is finalized, but the proposed syntax looks like this:

:root {
    var-header-color: #06c;
}
h1 { background-color: var(header-color); }

The first rule is the new variable syntax and defines a property named “var-header-color” on the root element. Then you can use that variable throughout your stylesheets with the var(header-color) syntax. Also note that you can use variables within variables like this:

:root {
    var-my-color: #06c;
    var-background: linear-gradient(left, var(my-color), white);
}

There are some more examples of how to use variables on the W3C page, as well as in WebKit’s test suite.

The bad news is that variables aren’t backwards-compatible at all. Older browsers will simply ignore them (right now all browsers will ignore them) and if you’re defining key elements like background colors with variables the results in older browsers won’t be pretty. Eventually old browsers will fade away and CSS variables will probably become commonplace, but for the next few years at least we suggest looking to a preprocessor if you simply must have your variables.