CSS

Introducing CSS variables

If there is one thing a language needs to qualify as a programming language, it’s variables; they’re incredibly useful, save us a bunch of work and typing, and improve coding all-round.

This is exactly what CSS didn’t have. Pre-processors like Sass and Less used them, but vanilla CSS never had variables. Until now.

They’ve been on the horizon for a while, but only recently have variables started to be implemented in CSS, let’s take a look at how they work.

Browser support

Currently CSS variables are only supported by Firefox Nightly and consequently, we really can’t use them. However, this is very much a beta-state and we expect to see them implemented elsewhere soon.

For Webkit browsers there is already a trac to get variables up and running and for some versions of Chrome variables were available by activating a flag in chrome://flags and using the -webkit- prefix.

For IE, unfortunately we have to wait and see what the next release brings.

How to use CSS variables

We all know how variables work, the only variation is the syntax. This is how we’ll declare variables in CSS:

var-variable-name: value;

Global variables

As with other programming languages, we can also set variables as global, like so:

:root {
var-blue-color: #2980A6;
var-text-color: #E0E0E0
}

I’m using the root pseudo element because this way, the highest level parent in the DOM will be the one holding these variables and they will work down the DOM tree to all our elements.

When it comes to applying variables, we use the var() function to call the variable, like so:

.test {
background-color: var(blue-color);
}
p {
color: var(text-color);
}

Since we declared the variable in the root of the document we can use it anywhere.

Scoped variables

In addition to global variables, we can also set a variable on a particular element, where its value will change:

.one {
var-blue-color: #004F70;
}
.one a {
color: var(blue-color);
}

In this particular case the anchor tags will inherit the new values we set in their parent element but anything outside that div will use the one we set in the root of the element.

Conclusion

CSS variables will be a great help when they’re finally available in the not-too-distant future. They may even herald a migration away from pre-processors and back to vanilla CSS.

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website. More articles by Sara Vieira
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress