Change your life with CSS Variables

Change your life with CSS Variables

We all know and love using variables in our SASS files, it’s basically the most often used selling point for SASS and LESS and along with things like mixins and nesting it’s what I use the most out of all of those tools’ features.

Using CSS Variables

CSS Variables are super easy to use. If you’ve used a CSS preprocessor before you already know how they work and why we’d use them. I’ll give the rest of the audience a quick run through though.

CSS is a pretty basic style language, we start with a class, ID or element and then put in individual styles for individual properties. This is great when you’re working solo on your personal web page in 2002 but now we’re in the world of huge enterprise sites and abusing browsers into launching our new marketing campaigns with thousands of lines of CSS.

Developers began dealing with this by using tools like SASS and LESS to include files, run functions and most importantly for us, define variables.

Imagine for a minute you’re building a website and that website uses the colour “#008767” as it’s primary colour. This site might use this one colour in a whole lot of places.

An example of this could be that the background for one component is this colour while the link colour in another component is this colour, we might also want to set the border for a component to be this colour too.

In regular CSS we would set all of these properties individually for each of the components we want to change. This is okay for small applications but when you’re working on something large it can become really difficult to track what is equal to what and if you or your client ever decide to change the colour you’ve set then you have to find every instance and hope that you catch them all before the next deployment.

If we use a variable we’re able to define our colour in one spot and if we ever need to change it we just update the definition and all the references will update automatically. Fantastic!

Show me the variables

Enough of this introduction stuff, you came here to change your life with CSS variables and that’s what I’m going to give you.

First off, all variables are prefixed with --. This is an immutable truth. We also define our variables within a HTML element, similar to any other style. A good way to organise your variables is to put sitewide variables in your body element. This looks like the following:

body {
  --primary: #00c;
  --secondary: #333;
  --accent: #0cc;
}

We define our primary, secondary and accent variables. All of these are colours but we can also use variables to define basically anything, heights and widths, sizes, colours and positions. Anything that you can write out with CSS you can start to replace with variables.

Next, if we want to start using variables it’s really easy. We apply them to our element and call the var keyword.

.item {
  border: 1px solid var(--accent);
  color: var(--primary);
}

As you can see in the example above we can apply this to a property that takes a single value or place a variable within shorthand syntax that takes multiple arguments such as the border shorthand.

This is easy!

Nesting and Redefining Variables

Next we’ll explore another feature of CSS variables.

Imagine for now that we have our previous CSS with all of our variables defined but for whatever reason we want to have a different value for our variable, maybe we want to change the colour for some reason.

We can redefine and use our variable like so:

.full-width-component {
  --secondary: yellow;
  color: var(—secondary);
}

What’s really cool about this is that the variable is only changed within the scope of the .full-width-component class and it’s children. Our variable remains untouched for all other classes, IDs and elements. Great!

Having the power to set global and local variables is BIG news in the world of CSS.

Things that don’t work

In the course of writing this post I tried out a few things that I do using SCSS that I wasn’t able to recreate using CSS variables. Most of my learning about CSS variables has come from other blog posts and I haven’t kept up with the development of the spec so some of these might be coming in future releases, some might not be. Only time will tell.

We can’t use a variable to redefine itself

Something I can do using SCSS is:

$myvar = 16px;
$myvar = calc($myvar * 2);

Using CSS variables this isn’t possible, which is a bit lame but that’s okay.

Can’t use a variable for media query string interpolation

One of my favourite things to do in SCSS is to use variables for media queries. I knew going into it that I wouldn’t be able to push an entire string into a variable but I wanted to try anyway.

SCSS:

@media #{desktops-up} {
  .my-class { color: #333; }
}

What I tried with CSS:

body { —mobile: 768px }

@media (min-width: var(—mobile) {
  .my-class { color: #333; }
}

I suppose this didn’t work because I can’t define my variable outside of an element and I can’t define my media query inside of my body element. SCSS handles all of this with ease so it’s one on the board for preprocessors.

Would I use it over SCSS?

Maybe. There’s still some things to be included like I listed above but one of the biggest plusses for me is that variables coming from CSS are presented in the browser as having their name, eg: color: —primary in the inspector tools. This, I feel, is far superior to SCSS where the variable’s values are literally put in place so it looks like color: #333;. This might not seem like a big deal and maybe is even preferable in some cases but it can become a real pain when debugging and trying to change values in many places. While writing this article I was able to modify my variable definitions in Chrome’s inspector and have those changes be applied instantly to all of the elements that called on those variables.

Browser support right now is mostly good if you’re not using a Microsoft product. Chrome, Firefox, Safari and their mobile equivalents all support CSS variables and follow the spec. Edge has partial support and has some known bugs. The Edge team is working hard so I’m sure they’ll be ironed out. The problem children as always are the core IE versions. Anything less than 11 isn’t going to work. Check out the CanIUse page for more information.

CSS variables, like CSS grid and Flexbox are going to have a big impact on the way we write code. It’s not time for getting rid of your preprocessor yet and there’s still a lot of worthwhile functionality to have there but as our base tools become more robust our advanc ed tools can as well. Hopefully we’ll see some optimisations coming out of other software in the future.

I hope you’ve enjoyed this post and learnt something new about CSS variables. If you’d like to receive an email every time I post some new front-end information please subscribe to the mailing list. The emails are infrequent and I try to make them good.

Check out the Codepen of a small CSS variable project I built for this post demonstrating some of the features: https://codepen.io/Haydos585/pen/eWeEOW.

About Nick

Melbourne based web developer that loves Laravel, Ruby on Rails, Phoenix/Elixir, Writing, Travel, Jiu-Jitsu and Starcraft.

www ·

Leave a Reply

Your email address will not be published.