Imagine this scenario: You’ve just finalized the latest draft of your website. Everything works as planned, and since you spent a little time brushing up on CSS, it looks great too.

Then your manager shoots you an email. They love the site, but they’ve asked you to change the light purple color of your backgrounds to something a bit more earthy.

That’s no problem. You just need to find a new color, then open up your CSS files and substitute the purple value in one spot, and another spot...and here...oh, and here, almost missed that one...

“Okay,” you say some time later, “I got them all. Probably.”

This scenario demonstrates one drawback of CSS: With all the style rules that need to be applied to multiple elements on multiple pages, things can get pretty redundant. And redundancy can eat up your time and cause friction whenever you need to change a color, font, or any other style aspect across your site.

Luckily, there’s a better way to code in CSS: with CSS variables.

After getting the hang of CSS basics, CSS variables are the next step to take your front end development skills up a notch. They’ll make your CSS code tighter, cleaner, and easier to edit in bulk. In this post, we’ll show you what makes CSS variables so useful, and how you get started with them.

Free Intro Guide to HTML & CSS [Download Now]

What are CSS Variables?

In computer programming, a variable is a unit that stores an assigned value. Variables are fundamental to all computer programs because they enable computers to store, use, and manipulate information.

Therefore, CSS variables are special style variables that can be used throughout a CSS document. But how is this different from regular CSS?

Normally when you write a declaration in CSS, you state the property — the style targeted by the declaration — followed by the value — the type of styling to be applied. This declaration is assigned to a CSS selector, like so:

 
div { background-color: green; }

For a while, this was the only way to assign values to properties in plain CSS because, until recently, CSS did not have variables. If you wanted something resembling variables in CSS, you would need to use a CSS preprocessing language like Sass (which is incorporated into frameworks like Bootstrap).

However, CSS variables now provide an alternative means style to our page elements without needing an add-on solution. Also called custom properties, CSS variables let us create our own custom values so our code is easier to understand and edit. Let’s unpack how to use them.

Declaring CSS Variables

To use a CSS variable, we first need to declare one. CSS variables can take on any CSS value — for this example, we’ll use color values (represented as hex codes) and font families.

To declare a CSS variable, write it inside a rule set like you would any other CSS declaration. The difference is that the property of a CSS variable always begins with two dashes, followed by a name you assign it. For example:

 
p {

--main-text-color: #ff7a59;

--main-text-font: 'Avenir';

}

Here I’ve created two custom properties: --main-text-color assigned the hex value #ff7a59 (a nice shade of orange), and --main-text-font assigned the typeface ‘Avenir’.

Note that custom property names are case-sensitive. A CSS variable named --main-text-color will be interpreted as different from --Main-Text-Color. It’s a good idea to avoid capital letters in your variable names to prevent such confusion.

Using var()

Up to this point, we’ve only created our CSS variables. We haven’t yet assigned them to any HTML selector, so the CSS variables won’t affect anything on the page.

To apply our CSS variables to HTML, we use the var() function. In programming, a function is a section of code that completes a task. Functions are often indicated by parentheses following the function name.

The job of the var() function is to find a particular CSS variable and apply it to a selector. It is written as follows:

 
var(--css-variable-name)

...where --css-variable-name is the CSS variable you want to apply.

In our example, we can apply our CSS variables to a selector like so:

 
p {

--main-text-color: #ff7a59;

--main-text-font: 'Avenir';

color: var(--main-text-color);

font-family: var(--main-text-font);

}

In this code, we use var() twice. First, var() finds the value of the --main-text-color custom property that we made, then applies this value (#ff7a59) to the color of any text inside a <p> tag.

Next, var() takes the value of --main-text-font and applies this value (‘Avenir’) to the font-family property of text inside <p> tags.

When applied to this HTML:

 
<h2>This is an H2 without styling</h2>

<p>And this is a paragraph with styling.</p>

...we get this page rendered in the browser:

an example of html styled with css variables

Inheritance With CSS Variables

Like with normal CSS, child elements inherit the CSS variable values of their parent elements (as long as the parent value is not overwritten in the child element). Consider the following HTML and CSS:

 
<!-- HTML -->

<body>

<div id="section-1">

<h2>Section 1</h2>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>

</div>

<div id="section-2">

<h2>Section 2</h2>

<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.</p>

</div>

</body>

 
/* CSS */

:root {

--main-background-color: #93e9be;

--main-text-color: #ff7a59;

}

div {

background-color: var(--main-background-color);

}

#section-1 {

color: var(--main-text-color);

}

Because we assigned the --main-text-color value to the first div, both its child <h2> and <p> elements inside it inherit this custom variable:

an example of html modified with css variables

Scope and CSS Root Variables

You might have noticed that in the previous example I declared my CSS variables with a selector called :root. What does this mean?

When you declare a CSS variable, you also give that variable a scope. A variable’s scope determines where that variable will work, based on where you declare it. CSS variables can have either local or global scope.

Local CSS variables only work in the selector they’re created inside. Let’s illustrate this by modifying the above example: What happens if I take the --main-background-color declaration and move it to the #section-1 selector?

 
:root {

--main-text-color: #ff7a59;

}

div {

background-color: var(--main-background-color);

}

#section-1 {

--main-background-color: #93e9be; /* this line was moved from :root */

color: var(--main-text-color);

}

Well, since --main-background-color is now declared in #section-1, its scope has been changed. This variable will now only work in the first div, not the second div:

an example of html modified with css variables

This happens because the --main-background-color variable is “local” to #section-1.

On the other hand, CSS variables that work throughout an entire document are called global CSS variables. We make global CSS variables by writing their rules for the :root selector. :root applies to the topmost element in the HTML document object model which contains all other elements, <html>.

While you can declare CSS variables in any CSS selector you want, it’s a common practice to declare all or most CSS variables in :root so they will work universally in the document.

Fallback Values

Every time you use var(), you must specify a CSS variable inside the parenthesis. You also have the option to write a fallback value, a CSS value that is applied if your CSS variable doesn’t work for some reason. This could be due to a typo somewhere in your CSS, or the browser being unable to render the value you specify for your variable.

Fallback values are placed within the parenthesis of the var() call after the first argument, the CSS variable name. The two arguments are separated by a comma. A fallback value in our example looks like this:

 
p {

color: var(--main-text-color, #ff4500); /* #ff4500 is the fallback value */

font-family: var(--main-text-font, 'Helvetica'); /* 'Helvetica' is the fallback value */

}

You can even add multiple fallback values for the same CSS property in case your first fallback doesn’t work. In this case, fallback values are written in a list separated by commas, and are applied in that order:

 
p {

font-family: var(--main-text-font, 'Helvetica', 'Arial', 'Courier');

}

While optional, a fallback value ensures that some desired styling will be applied in case of an error with your CSS variable.

Why Use CSS Variables?

We’ve learned a lot about how to use CSS variables, but why exactly are they useful? In this section, we’ll cover three main benefits to custom properties: They enable bulk editing, dynamic styling, and better readability.

Bulk Editing

If you have one style rule (e.g., a color, font, etc.) that you want to apply throughout your website, you’ll probably need to write it in multiple places throughout your code. Larger websites may have the same style rule written out dozens or even hundreds of times.

But, what if you want to change the rule? In traditional CSS, you would have to change each instance of the rule in the code, which gets repetitive very fast. Even with a find-and-replace feature, this process is inconvenient, tedious, and prone to errors.

This brings us to perhaps the biggest advantage of CSS variables — they allow you to apply widespread style changes with minimal changes to the code.

Imagine that one of your brand colors, Seafoam Green (represented by the hex code #93e9be), needs to be applied to backgrounds, text, and icons across your site. With your new knowledge of CSS variables, you can create a custom property for your shade of green:

 
:root {

--brand-green: #93e9be;

}

Then, apply this value to your desired elements:

 
div { /* this can be any element */

color: var(--brand-green);

}

If at any point you need to adjust this shade of green, you just need to change your CSS variable declaration.

 
:root {

--brand-green: #55c98f; /* that was easy */

}

This change will automatically be applied to all elements given the value var(--brand-green) — no more tracking down every instance of the old color and changing it.

Dynamic Styling

CSS variables allow us to change page style elements dynamically — in other words, without needing to reload the page.

This ability is especially handy for responsive design. When used in conjunction with media queries (a CSS feature that detects device properties like screen size), CSS variables can make elements to adapt to the viewport size.

For example, let’s apply this CSS to a <div> element:

 
:root {

--div-width: 1000px;

--div-height: 250px;

--brand-green: #93e9be;

}

div {

width: var(--div-width);

height: var(--div-height);

background-color: var(--brand-green);

}

@media (max-width: 1000px) {

:root { --div-width: 500px; }

}

In the :root and div selectors, we specify the width, height, and color for our <div>. The following media query instructs the HTML to change the our --div-width value only if the screen width dips below 1000 pixels wide. So, we end up with this:

an example of a div that changes its width based on the width of the browser window

This effect will apply to any <div> element, and any additional element with the width: var(--div-width) declaration assigned to it.

Readability

One last bonus: CSS variables can be written in a way that makes it easier for human programmers to understand. If you just see hex code #93e9be, you won’t know what color it produces, while --brand-green makes clear the purpose of the variable.

Save Time With CSS Variables

Once you’ve mastered the basics of CSS, incorporating CSS variables into your programming vocabulary will save you huge amounts of time in the future. From small tweaks to full-blown rebrands, it’s helpful to format your CSS in a way that can be read and modified quickly and smoothly.

Of course, the concepts I’ve explained are just the basics. Feel free to experiment further: Control your variables with JavaScript (here’s a good tutorial to get started), experiment with the calc() function, and see what engaging, high-converting projects you come up with.

New Call-to-action

 css introduction

Originally published Nov 2, 2020 7:00:00 AM, updated December 02 2020

Topics:

Bootstrap & CSS