CSS variables (or officially: custom properties) in pure CSS are a huge time saver for anyone willing to invest five minutes into learning how to use them. They’ve been around since CSS3, and 92% of all users have browsers that support them. Using CSS variables doesn’t require any significant changes in existing stylesheets or new tools and can be easily applied to old projects. Instead of having a hex color code written down in hundreds of places in a file, you can have it defined in just one place – with a CSS variable. A huge time saver and help in making stylesheets more consistent.

CSS variables in pure CSS:

  • no additional tools, software or “special” changes to existing stylesheets are needed
  • 92% of all users have browsers that fully support CSS variables
  • old projects can easily be retrofitted to use them
  • CSS variables provide consistency, tidiness, and speed in stylesheets of all sizes
  • if you know CSS you’ll get the hang of them in minutes

Wait, so this is Saas or Less, right?

No, we are talking about pure CSS here, not CSS coupled with a preprocessor like Saas, Less or SCSS. Using CSS variables does not require any additional tools, editors, or changes in your workflow or anything else that you use. Therefore, existing CSS files with no variables don’t require any “special” changes, and you can mix and match – use variables only for parts of the file, or only in some files is your project.

CSS preprocessors like Saas or Less support variables too. Also, they have a lot more functions and options you can use. However, as the name suggests, they require a preprocessor – a tool that converts CSS written in Saas into pure CSS. If you only need variables – pure CSS has everything you need.

CSS variables are a native function, and that’s what makes them great. With minimal effort, your stylesheets are much much more readable and consistent. Moreover, any changes that you have to do later on are much easier to do – certainly faster than doing search&replace when you need to change a color code in hundreds of places.

Let’s create some variables

Like in any programming language, there are two steps to using variables: giving them value (defining them) and using them (putting them in all places where you need that value). We’ll do the same;

:root {
  --my-red: #ff0080;
  --my-shadow: 3px 3px 10px green;
  --my-border: 1px solid #222222;
}

.custom-box {
  box-shadow: var(--my-shadow);
}

.custom-text {
  color: var(--my-red);
  border: var(--my-border);
}

If you want to use a variable globally (anywhere) in the CSS file, you have to define it in the :root pseudo-class. The location in the file doesn’t matter. It can be at the beginning, or the end of the file. But, you have to put the variable in :root. The name has to start with a double dash -- and can’t contain any spaces. CSS variables can hold any value that you usually assign to a CSS property; from simple values like colors to complex expressions for shorthand properties like the background or shadow.

To use a variable (to get its value) place it in the var() function. Don’t forget that all variable names start with --. That’s everything you need to know to get started.

Using fallback values

In case a variable isn’t defined a fallback value can be provided to the var() function as the second parameter.

:root {
  --my-red: #ff0080;
  --my-blue: #0020ff;
  --my-shadow: 3px 3px 10px green;
}

.custom-box {
  box-shadow: var(--my-shadow, 2px 2px 5px blue);
}

.custom-text {
  color: var(--my-red, var(--my-blue, red));
}

Don’t worry if the property value is a complex one. The fallback parameter does allow commas (see box-shadow example). It also allows for chaining of multiple var() functions as shown for color in .custom-text. If --my-red and --my-blue variables are undefined, then red will be used as the color.

Combining var() and calc() works too, without any surprises in the syntax. Here’s an example that includes a local variable that’s only available in the class it was defined in.

.box {
  --padding: 10px;
  
  height: calc(var(--padding) + 100px);
  padding: var(--padding);
}

Use calc() sparingly. It’s not a bad thing but when overused gets quite problematic to debug and maintain.

Getting and setting CSS variables via JavaScript

By using plain JavaScript, you can set new CSS variables and access their values. I don’t use this method. Instead, I prefer changing the element’s class. However, there’s nothing wrong if you want to access CSS variables via JavaScript. It’s certainly usable in some situations. Those who stick to jQuery, can convert the code to a jQuery plugin.

To create a new variable, or change the value of existing one use:

// set var value
document.documentElement.style.setProperty('--my-var', 'blue');

Accessing a variable is a bit more complex. If the variable is defined via JS then use:

// get var value if defined via JS
document.documentElement.style.getPropertyValue('--my-var');

However, if it’s defined via CSS (and it usually will be), use this code:

// get var value if defined via CSS
getComputedStyle(document.documentElement,null).getPropertyValue('--my-var');

Problems and things to look out for

Now that you know how to use variables, don’t go overboard with them and create a variable for every single property value in the stylesheet. For instance, this would be overkill and abuse of the whole concept;

:root {
  --spacing-10: 10px;
}

.custom-box {
  padding: var(--spacing-10);
}

You achieved nothing. Just got --spacing-10 instead of 10px. You’ll soon end up creating twenty more variables for every padding pixel value there is from 5px to 100px. If you’re going for consistency then go with a concept of --small-padding, --medium-padding, --large-padding and assign appropriate numerical values.

Although not required by CSS standard I wholeheartedly suggest defining all variables in one place and at the beginning of the CSS file. That way, you’ll always know where they are and can swiftly change values. If you scatter definitions all over the file, you’ll have a hard time tracking things and might end up defining the same variable in multiple places. Debugging that won’t be a fun task.

There’s no reason not to use CSS variables

On the Internet, things move forward fast (like cookies being replaced by local storage). For big projects and big teams switching to CSS preprocessors like Saas is the right way to go. However, for smaller projects or existing projects that require maintenance, CSS variables in pure CSS are the right solution. They require absolutely no changes, software or tool upgrades or anything. You define a variable and start using it.

Isn’t it better, faster, and more reasonable to define a color code once and then use a variable throughout the file instead of having the same hex in a hundred places?


Leave a Reply

Your email address will not be published. Required fields are marked *