TABLE OF CONTENTS

CSS Variables: what they are and how to use them?

How to use CSS Variables

Introduction

In programming, variables are the basic building blocks of any software application. They store assigned values that can be manipulated and used in any part of the program.

Thanks to that, the code is less redundant and more maintainable. That’s why they are so fundamental for software development.

In this article, we will take a closer look at their equivalent in the CSS world.

What are CSS Variables?

Even though CSS (Cascading Style Sheets) is not technically a programming language it has its own version of variables that were introduced in Chrome 49 and gained popularity since then.

CSS Variables, also known as “CSS custom properties“ added more flexibility to frontend workflow. From the day it was released, we are able to declare, use and manipulate variables that can be reused across bare CSS files.

For a long time, the only way to achieve the same result was to use CSS preprocessors like Sass or LESS.

How to Use CSS Variables

CSS Custom property declaration

To declare a variable in CSS, we need to add a name that will be prefixed with two hyphens () and assign a value after the colon. In the example below the selector and its children has the access to the variable declared inside.

selector {
--variable-name: value;
}

Declaring a variable in the :root element will give it global scope, so all descendant elements can access it.

:root {
–-bg-color: #f5333f;
}

Using CSS Variables

To apply our CSS variables to the desired elements, we use the var() function and add our variable name inside as an argument. The task of this function is to find a CSS variable and apply it to a selector.

div {
background-color: var(--bg-color);
}

CSS variables inheritance 

Just 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). Let’s look at the example below:

HTML:

<div class="container">
    <div class="inner">
        <div class="box box-one">Box one content</div>
        <div class="box box-two">Box two content</div>
    </div>
</div>

CSS:

.container {
--padding: 1rem;
}
.inner {
padding: var(--padding)
}
.box {
padding: var(--padding)
}
.box-two {
--padding: 2rem;
}

The .inner and .box-one elements will have the same padding (1rem) that has been declared in their parent with class .container. Only the padding of .box-two will be different because it has been overwritten inside its selector to the 2rem value.

READY TO START YOUR NEW PROJECT?

Fallback values

When using CSS variables we may accidentally refer to a variable that doesn’t exist in the document. Sometimes it’s just a typo in the variable name that we want to use. In this case, adding a fallback value should prevent unwanted display behavior. It can be also used for debugging if the proper variable name is added.

The fallback value should be added after the variable name in var() function and separated by a comma.

element {
  property: var(--variable-name, fallback-value)
}

Please notice the misspelled variable name used on the div element in the example below. The –color-primary was not defined in the document so the background color shouldn’t be styled as #000, but since we’ve added a fallback value the color will be applied even if the CSS variable does not exist.

:root {
--color-primary: #000;
--color-secondary: #fff;
}

div {
  background-color: var(--colour-primary, #000)
}

Invalid values

When a CSS variable value isn’t valid to a property that is provided it will be applied (you can check in dev tools) but it won’t work.

For example, suppose we use a variable that holds a value of #fff on a font-size property, which is valid for color or background properties. In that case, the browser will determine that it is invalid for font size and set its default value.

div {
--main-text: #fff;
font-size: var(--main-text);
}

CSS variables with CSS calc()

The calc() function can be very practical with CSS variables. For example, we can create a base size for a component and then change only one variable to make it smaller or bigger.

Let’s suppose that we want to have different variations of the user’s .avatar.

.avatar {
--size: 4; 
width: calc(var(--size) * 1rem); /* 64px */
height: calc(var(--size) * 1rem); /* 64px */
}

In this example, we assigned the number 4 without any unit to the CSS variable –size. We then used it to get new width and height values with a unit by multiplying them by 1rem to become 4rem (64px).

.avatar--small {
--size: 2; /* 32px */
}

.avatar--large {
--size: 8; /* 128px */
}

With that, we can create variation classes by just adding the –size CSS variable to the modifier class.

Usage of CSS Variables with JavaScript

Just like every other part of a webpage, you can get and manipulate CSS variables values with JavaScript.

In the example below we will be changing the page background after selecting the different color in the input and applying it to the body of the document.

Let’s start by adding a very simple HTML markup with just an input element with the type=”color” to the document body. It will be our color picker for the page background.



  
    <title>Setting Page Background with CSS Variables and JavaScript</title>
  
  
    
  

Then we will add some base CSS styles:

  • We will assign –page-background variable to the background-color property of the body element
  • We will use a flexbox just to center the input horizontally and vertically on the page.
  • In the end, we will add a height of 100vh for the document body element to take 100% viewport height
:root {
--page-background: #f5333f;
}

body {
  background-color: var(--page-background);
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

Finally, we will add a simple JavaScript code that will make the magic happen.

Just 3 lines of it will do the job and our functionality would work as expected.

document.querySelector('input[type=color]').addEventListener('change', (e) => {
  document.documentElement.style.setProperty('--page-background', e.target.value);
});

As you can see manipulating CSS Variables with JavaScript is pretty simple and for sure can be used for different use cases.

Browser compatibility for CSS VARIABLES

While CSS variables are a very useful functionality, they’re only useful when they are compatible with our browser. Take a look at the chart below to see browser compatibility for this CSS feature:

CSS Variables compatibility with the browsers

You can check out CanIUse for more details on browser compatibility for the CSS Variables.

Conclusion

Incorporating CSS Variables into your development process will improve the way you build your projects. It’s helpful for formatting your CSS in a way that can be read and modified quickly and efficiently, allowing you to write reusable and high-quality code.

There are many ways in which CSS custom properties could be used, so we simply recommend giving them a try on your projects.

Thank you for reading!

Article link copied

Close button