CSS Variables

Posted on: June 28th, 2018 by alemieux

I’m not a fan of LESS or SASS, at least for my workflow. In marketing, I usually am designing landing pages or one-off experiences that don’t require a ton of styles to manage. I’m not collaborating with other designers who are also in the same code as I am.

I have played around with SASS, so I was familiar with the concept of setting variables. Having read a few articles on CSS Variables (Custom Properties), I was blown away by the utility of it. To set a property once and apply it throughout a design so that if and when it changes, it ripples through and changes it everywhere. That’s pretty powerful for CSS, which isn’t a programming language.

Support is pretty good except for IE and Opera Mini, but no surprises there. All of the major vendors do support it.

There are a couple of ways to implement vars in your stylesheet, but I feel like the most useful way is to use it in the :root selector, which is a unique selector that can store all the variables for your web application in one place. Here’s an example:

:root {
–purple: #cc69a7;

Notice the syntax of the variable is two dashes followed by the name of the variable and its property. The :root selector will have effect throughout the stylesheet and can be overridden in other selectors by declaring variables within them and using them there.

To apply a variable to a property within a selector, you use the var() command and call on the name of the variable:

.header {
background-color: var(–purple);

Variables can contain property values for color, font-family, box shadow, and any other property you can think of. It’s pretty amazing when you begin to realize the power of setting things for consistency throughout a design.

Here’s a basic code example:

See the Pen CSS Variables test by Al Lemieux (@alemieux) on CodePen.

Without a doubt, I’ll be putting this to good use in the future.

Tweet this! | Bookmark at Delicious

Comments are closed.