The WordPress Specialists

Guide to Understanding CSS Variables

G

CSS Variables (also referred to as cascading variables or custom properties) are style sheet language entities that contain specific values that can be reused throughout a web document.

CSS Variables are style sheet language entities used for the purpose of circumventing repetitive styling tasks – repeating values – while writing style sheets for web pages.

For instance, if your website’s main color is green and you want to apply the color to various HTML elements throughout the website. The ideal concept is to declare the color a CSS variable so you could reference it for each of the elements in your style sheets.

It’s possible to manually set the color at the different places such as headings, buttons, links, borders, navigation bar, etc. but how do you handle it if you later decide to adjust the color? Having to adjust the colors in this scenario is always a difficult part of web development, mostly if you are building a website with several pages.

CSS variables solve this challenge by allowing you to store those values as entities so you can reuse and adjust the properties of several elements in one place anytime you desire. This will save you the time and resources required to search, track and change each color and styling manually.

CSS Variables

Before the introduction of CSS variables, most developers use CSS preprocessors such as LESS and SASS to tackle this challenge while also adding some dynamic capabilities to CSS coding such as control over bulk CSS values. But this doesn’t make CSS variables irrelevant. We’ll discuss more on this in a later section.

Syntax: how to declare and use a CSS variable

A custom property notation — is used while defining CSS variables. And just like variables in other languages, they are written like regular properties but start with the notation. A var() function is used to retrieve the variable each time you want to use it.

How to declare a CSS variable

  1. item {
  2. –main-color: green;
  3. }

How to retrieve the CSS variable

  1. item {
  2. color: var(–main-color);
  3. }

While writing CSS properties such as a background-color, you may choose to use a particular type of green in the hexadecimal system, which cannot be represented using a name in your style sheet. These RGB values would feature in several lines alongside other unique colors in your CSS document as shown in the example below:

  1. html, body {
  2. background: #98FB98;
  3. color: #fbfb98
  4. }
  5. h1, p {
  6. color: #fbfb98;
  7. }
  8. #navbar a {
  9. color: #fbfb98;
  10. }
  11. .item {
  12. background: #fafaf5;
  13. }
  14. button {
  15. background: #fbfb98;
  16. color: #ffab0f;
  17. }

Reviewing this style sheet could be very confusing, mostly if you want to effect changes. Of course, your CSS document for a large website won’t just be 21 lines. Let’s see how it looks if we store those colors as CSS variables and reuse them accordingly.

  1. :root {
  2. –green: #98FB98;
  3. –yellow: #fbfb98;
  4. –red: #e60f00;
  5. }
  6. html, body {
  7. background: var(–yellow);
  8. color: var(–green);
  9. }
  10. h1 {
  11. color: var(–green);
  12. }
  13. #navbar a {
  14. color: var(–green);
  15. }
  16. .item {
  17. background: var(–red);
  18. }
  19. button {
  20. background: var(–green);
  21. color: var(–red);
  22. }

Using CSS variables, the document became more readable and more semantic. Most importantly, any change to the entities will automatically update the color values of all elements associated with the CSS variable. And that perfectly limits repetition in your CSS document.

Scope of CSS variables and overriding

Similar to other programming languages, custom properties can be global or local, which depends on where they are declared.

Variables declared in the pseudo-class (:root selector) can be accessed as global variables while those within a CSS block of a specific selector are local variables accessible within the block they are declared.

Global CSS variables

Global CSS variables can be accessed from anywhere in the CSS document. A typical example is in the previous example; –green, –yellow and –red variables are accessible throughout the document because they are declared inside the :root selector.

Local CSS variables

In a local scope, CSS variables are accessed only within the block they are declared. This type of scope is important when we want to limit the value to a particular element or section of a page. For instance, we can limit the accessibility of –red variable to only elements in the item class by declaring and accessing it inside the class block.

  1. .item {
  2. –red: #e60f00;
  3. background: var(–red);
  4. }

By this, only elements inside (or nested inside) the class can access the –red variable, and this makes the custom property only functional within the local scope it’s declared.

Hoisting in CSS variables

Similar to what we have in JavaScript, you can hoist CSS variables, though this should not be habitual. CSS variables are hoisted when they are declared after they have been used. Please see the example below.

  1. }
  2. html, body {
  3. background: var(–yellow);
  4. color: var(–green);
  5. }
  6. :root {
  7. –green: #98FB98;
  8. –yellow: #fbfb98;
  9. }

Ideally, this should bring errors if we want to consider how lines of code are executed. But the code above works perfectly fine. This is because compilers usually arrange all variables at the top first before executing our codes. Hence, regardless of where the variables are declared within a selector, they are first compiled before other codes in the block.

Overriding CSS variables

The scope at which a CSS variable is declared also affects the authority it has over the elements on which it is used. This is clearly explained by the value overriding of CSS variables due to where the values are declared. If we can declare a variable with the same name in different scopes; locally and globally, the values in the local scope, which is more specific, will claim the properties of all elements referencing it within the block.

  1. :root {
  2. –green: #98FB98;
  3. –yellow: #fbfb98;
  4. –red: #e60f00;
  5. }
  6. html, body {
  7. background: var(–yellow);
  8. color: var(–green);
  9. }
  10. h1 {
  11. –green: #3e803e;
  12. color: var(–green);
  13. }
  14. #navbar a {
  15. –green: #55d455;
  16. color: var(–green);
  17. }

In the example above, the h1 and #navbar will display the –green values declared locally. Hence, the new shades of green will override the globally declared –green variable.

Theming with CSS variables

CSS variables are quite useful in theming a website. You may wonder if it has to do with allowing your clients to switch themes. Well, it’s not. There may be a need to mark a specific product, item or section on your website differently, such as making a product to stand out or have slightly different CSS styling from the rest.

You can use CSS variables to update a new styling of your featured products or items without having to restructure your previous code or write too many new lines.

By giving the section an additional class name, we can declare CSS variables of different values with the same name locally, within the class to bring about new styling. As mentioned previously, this will override the global variables referenced by all items, within the class we want to restyle. See the example below

Theming_with_CSS_1

To make “Product B” standout from the rest, we simply add featured class to the product class and re-declared the variables we want to change within the selector in our CSS sheet.

Theming_with_CSS_2

The different theme in the later image is achieved by including the lines of code below into our CSS sheet. We can as well change other properties by simply overriding their CSS variables in this selector.

  1. .box.featured{
  2. –green: #b9e03a;
  3. }

 

Building a responsive page with CSS variables

Style changes with respect to user devices controlled by some logical expressions known as media queries are easier to control using CSS variables. Media queries are the heartbeat of building a responsive page layout. The CSS changes as soon as the screen becomes less than or more than the author’s specified size.

For instance, we can set columns of the products in our previous example to stack on each other once the screen becomes 750px wide. At first, we will store the current column as a CSS variable, and use it in our current page layout and media query. Our page will become responsive to the set screen width as soon as we include the following code in our CSS style sheet.

  1. @media screen and (max-width: 750px) {
  2. .grid {
  3. –columns: 300px;
  4. }
  5. }

The grid column value is stored as –columns

The advantages of CSS variables over preprocessors

CSS variables offer so many advantages over preprocessors, which are simply programs seating on CSS. One very important advantage is that CSS variables have access to the DOM. This allows you to create local scopes – allowing CSS variables to work in a certain section of your app, effect changes using JavaScript for example if you want to enable your users to change the font-size of your page, and easily build a responsive page layout as seen in the example above.

CSS variables are easier to get started with – no transpiling is required as in the case of preprocessors. You don’t have to deal with all the problems associated with configuring a preprocessor such as path issues, wrong binaries, and native crashes. CSS variables are also perfect for themes, for example, if you want to make a product look different after it has been added to a shopping cart or selected by the user.

Coding

In addition to all the advantages of CSS variables over preprocessors already mentioned, you can define a custom property, use it in your early styling and override it later.

Conclusion

This article has briefly explained the meaning of CSS variables, how to declare and use them, a few cases where CSS variables are extremely important and lastly, the advantages of CSS variables over preprocessors.

Speed and flexibility is a crucial aspect of web development, and CSS variables control a large portion of these factors in your website styling. Proper implementation of CSS variables will make your code more readable, easier to access while also providing semantic meaning to your set values.

It’s absolutely acceptable to use preprocessors if you find other features important in your development cause. However, there are more advantages in writing pure CSS code aside from a need to transpile your codes to the understanding of a web browser.

What do you like most about CSS variables?

About the author

Ikechi Ude

Add comment

By Ikechi Ude
The WordPress Specialists