Using CSS Variables

Using CSS Variables

In this article, we will dive deeper into CSS variables (or custom CSS properties), which can be quite useful in reducing repetition in CSS code.

How to declare global CSS variables

Let's take a look at an example

:root{
     --main-background-color: #222831;
}
body{
   background-color: var(--main-background-color);
}

Declaring a custom property is done using a custom property name, main-background-color, which always begins with a double hyphen --, and a property value that is a valid CSS value, which for this case is a hex color code. It is best practice to define custom properties or variables on the root pseudo-class, so that it can be easily applied globally across the HTML document. The value can then be put to use using the var() function as shown above.

It is also worth noting that custom property names are case sensitive, meaning that text-color and Text-Color are treated as separate custom properties.

How to declare local CSS variables

Just as we have seen that CSS variables can be declared globally by defining them in the root pseudo-class, CSS variables can also be declared locally, which means that the variables will be limited to the scope of the element as such:

div{
    --div-color: #9fc131;
}

In the case as shown above, the variable having been declared locally, can be used by its children as shown below:

div p{
    color: var(--div-color);
    border: 1px solid var(--div-color);
}

Accesssing CSS variables using JavaScript

CSS variables can be accessed using JavaScript, which can prove to be a powerful tool for better user interactions. For example:

:root{
     --main-background-color: #222831;
     --text-color: #ffffff;
}
body{
   background-color: var(--main-background-color);
}

To grab the CSS variables into JavaScript, the code is as shown below:

const root = document.querySelector(':root');
const rootStyles = getComputedStyle(root);
const mainBackgroundColor = rootStyles.getPropertyValue('--main-background-color');

The getComputedStyle() method returns an object which contains the values of all CSS properties of an element. The getPropertyValue method returns a DOMString containing the value of a specified CSS property, which in this case is --main-background-color.

With this, we can update the CSS variables using setProperty as such:

root.style.setProperty('--main-background-color', '#9fc131');

Conclusion

Using CSS variables can be a powerful method to reduce repetition of code and increase readability, which can be a big win for front-end developers. Well at least, the struggle of manually updating values, for example, color codes, can be easily fixed using CSS variables.