Power-up Your Web Design with CSS Variables

When CSS was first introduced in 1996, it allowed web designers to make changes by updating a single stylesheet instead of hundreds of web pages.

As the popularity of CSS grew, so did its functionality. Today, one website can have hundreds or even thousands of values stored in stylesheets. However, when a designer wants to switch out colors or change font sizes, updating all those values can be more of a task than needed. That’s where CSS variables come into play.

Instead of changing one color hundreds of times, CSS variables allow a designer to change one value which affects everywhere that color is used.

Also known as “custom properties” or “cascading variables,” CSS variables allow values to be reused throughout a document. Let’s take a look at how CSS variables are used.

Some Examples of CSS Variables

Let’s say a site uses a complimentary set of colors for various buttons, banners, and backgrounds.

To define those colors using CSS variables, we first set a variable with a custom property notation (a double hyphen), like this:
–main-color: blue;

Then, where we want to add that color, we use the var() function, like this:
color: var(–main-color);

Once we declare a custom property with a double hyphen, the property value can be any valid CSS value, and added to a rule-set, like this:

element {
--main-background-color: blue;
}

A useful trick is to apply a CSS variable globally across an HTML page using the :root pseudo-class.

:root {
--main-background-color: blue;
}

Then, you call a CSS variable with the var() function, in place of a regular property value. Here’s an example:

element {
background-color: var(--main-background-color);
}

CSS Formats Worth Noting

CSS variable names are case-sensitive, so –background-color will be treated differently from –Background-Color.

Also worth mentioning, CSS variables are different from preprocessor variables, which look like this:

$background-color: blue;

That’s the SCSS variant of Sass, which a browser doesn’t understand on its own. Preprocessors are first compiled into CSS to work in browsers.

CSS variables, on the other hand, are readily understood in a browser.

The Takeaway

As websites rely heavily on CSS these days, anything that adds efficiency to the mix is a welcomed improvement.

CSS variables bring us back to the original intent of CSS—to centralize design—which boosts efficiency and saves time. And that’s a good thing for web designers.

See how Hall can help increase your demand.