A Practical Guide to CSS Variables (Custom Properties)

CSS Variables or Custom Properties

Preprocessors like Sass and Less certainly help to keep your CSS codebase organized and maintainable. Features like variables, mixins, loops, etc., by adding dynamic capabilities to CSS coding, contribute to minimize repetition and speed up your development time.

Lately, a few dynamic features have started to make their appearance as part of the CSS language itself. CSS variables or custom properties are already here and have great browser support while CSS mixins are currently in the works.

In this article, you’ll find out how you can start integrating CSS variables into your CSS development workflow to make your stylesheets more maintainable and DRY (Don’t Repeat Yourself).

Let’s dive right in!

What are CSS Variables?

If you’ve used any programming language, you’re already familiar with the concept of a variable. Variables let you store and update values your program needs in order to work.

For instance, consider the following JavaScript snippet:

[code language=”js”]
let number1 = 2;
let number2 = 3;
let total = number1 + number2;
console.log(total); // 5
number1 = 4;
total = number1 + number2;
console.log(total); // 7

number1 and number2 are two variables which store the number 2 and 3 respectively.

total is also a variable which stores the sum of the number1 and number2 variables, in this case resulting in the value 5. You can dynamically change the value of these variables and use the updated value anywhere in your program. In the snippet above, I update the value of number1 to 4 and when I perform the addition again using the same variables, the result stored inside total is no longer 5 but 7.

The beauty of variables is that they let you store your value in one place and update it on the fly for a number of various purposes. No need for you to add new entities with different values all over your program: all value updates happen using the same storage place, i.e., your variable.

CSS is mostly a declarative language, lacking in dynamic capabilities. You’d say that having variables in CSS would almost be a contradiction in terms. If front-end development were just about semantics, it would be. Fortunately, the languages of the web are very much like living languages, which evolve and adapt according to the surrounding environment and the needs of their practitioners. CSS is no exception.

In short, variables have now become an exciting reality in the world of CSS, and as you’ll soon see for yourself, this awesome new technology is pretty straightforward to learn and use.

Are There Benefits to Using CSS Variables?

The benefits of using variables in CSS are not that much different from those of using variables in programming languages.

Here’s what the spec has to say about this:

[Using CSS variables] makes it easier to read large files, as seemingly-arbitrary values now have informative names, and makes editing such files much easier and less error-prone, as one only has to change the value once, in the custom property, and the change will propagate to all uses of that variable automatically.

W3C Specification.

In short:

By naming your variables in ways that make sense to you in relation to your project, it’ll be easier for you to manage and maintain your code. For example, editing the primary color in your project will be much easier when what you need to change is one value for the --primary-color CSS custom property, rather than change that value inside multiple CSS properties in various places.

What’s the Difference Between CSS Variables and Preprocessor Variables?

One way you might have been taking advantage of the flexibility of variables when styling websites is by using preprocessors like Sass and Less.

Preprocessors let you set variables and use them in functions, loops, mathematical operations, etc. Does this mean CSS variables are irrelevant?

Not quite, mainly because CSS variables are something different from preprocessor variables.

The differences spring from the fact that CSS variables are live CSS properties running in the browser, while preprocessor variables get compiled into regular CSS code, therefore the browser knows nothing about them.

What this means is that you can update CSS variables in a stylesheet document, inside inline style attributes and SVG presentational attributes, or choose to manipulate them on the fly using JavaScript. You can’t do any of this with preprocessor variables. This opens up a whole world of possibilities!

This is not to say that you need to choose between one or the other: nothing will stop you from taking advantage of the super powers of both CSS and preprocessor variables working together.

CSS Variables: The Syntax

Although in this article I use the term CSS variables for simplicity’s sake, the official spec refers to them as CSS custom properties for cascading variables. The CSS custom property part looks like this:

[code language=”css”]
–my-cool-background: #73a4f4;

You prefix the custom property with two dashes and assign a value to it like you would with a regular CSS property. In the snippet above, I’ve assigned a color value to --my-cool-background custom property.

The cascading variable part consists in applying your custom property using the var() function, which looks like this:

[code language=”css”]

The custom property is scoped inside a CSS selector and the var() part is used as value of a real CSS property:

[code language=”css”]
:root {
–my-cool-background: #73a4f4;
/* The rest of the CSS file */
#foo {
background-color: var(–my-cool-background);

The snippet above scopes the --my-cool-background custom property to the :root pseudo-class, which makes its value available globally (it matches everything inside the <html> element). Then it uses the var() function to apply that value to the background-color property of the container with ID of foo, which as a consequence will now have a nice light blue background.

That’s not all. You can use the same nice light blue color value to style other color properties of multiple HTML elements, e.g., color, border-color, etc., simply by retrieving the custom property’s value using var(--my-cool-background) and applying it to the appropriate CSS property (of course, I recommend giving some thought to your naming convention for CSS variables before things get confusing):

[code language=”css”]
p {
color: var(–my-cool-background);

See the Pen Basic Workings of CSS Variables by SitePoint (@SitePoint) on CodePen.

You can also set the value of a CSS variable with another CSS variable. For instance:

[code language=”css”]
–top-color: orange;
–bottom-color: yellow;
–my-gradient: linear-gradient(var(–top-color), var(–bottom-color));

The snippet above creates the --my-gradient variable and sets it to the value of both the --top-color and --bottom-color variables to create a gradient. Now, you can modify your gradient at any time anywhere you have decided to use it by just changing the values of your variables. No need to chase all the gradient instances all over your stylesheets.

Here’s a live CodePen demo.

See the Pen Setting Value of CSS Variable with Another CSS Variable by SitePoint (@SitePoint) on CodePen.

Finally, you can include one or more fallback value/s with your CSS variable. For example:

[code language=”css”]
var(–main-color, #333);

In the snippet above, #333 is a fallback value. If fallbacks are not included, in case of invalid or unset custom properties, the inherited value will be applied instead.

CSS Variables Are Case Sensitive

Continue reading %A Practical Guide to CSS Variables (Custom Properties)%

Source: Sitepoint