12May
CSS variables
CSS variables

There are many ways we developers can take our design skills to the next level and working with CSS variables is one of those ways we can do this. Learn about CSS variables in the article and how you can use them to elevate your style game like a pro, keep your code efficient and easy to maintain, and change styles.

Introduction to CSS Variables

CSS variables are a way we can establish global and reusable values in our stylesheet and use them all throughout our project, they are also called Custom properties. They are adaptable to a wide range of settings, from colors to length, etc. In my opinion, one of the most significant advantages of using CSS variables is that I can avoid repeatedly duplicating the same value by storing it in a single location and then using it in various places across my CSS. Therefore, our stylesheets may become more structured, manageable, and amenable to alterations.

Why should CSS Variables be used

There are many reasons why CSS variables are important and should be used, but I will be leaving you with some of my best reasons why I use CSS variables:

  • They simplify the process of updating your stylesheets by allowing you to declare a value and use it in several parts of your code.
  •  They help you avoid having to repeatedly type the same data in your code.
  • They simplify your code, making it easier to understand and maintain.
  • They make it possible to save and retrieve information quickly and easily.
  • By giving variables custom names, they help you keep make your code easily understandable.
  • They’re crucial for making complicated software. Variables are a great method to organize and access data as your application expands in size and complexity.

 For instance, you can create a CSS variable for your Primary color, you can use this variable in multiple parts of your code and when you need to change it, rather than changing it on a different part of the code since it is a CSS variable all you do is simply change the variable value.

Declaring CSS Variables

Declaring a CSS variable isn’t so different from how properties are being assigned values. They are usually defined in a : root selector, just as the name is (root) it represents the root element of the document, and that’s why variables can be used everywhere in our stylesheet. they can also be declared within other selectors but their scope will be limited to children of that element.

Here are the steps you should follow when dealing with a CSS variable.

  1. Choose a descriptive name for the variable, that states the exact purpose of the variable, starting with a double hyphen (–). For example: --primary-color, --body-font-size, or --dark-background-color. you can be as descriptive as possible if you want.
  2. Define the variable inside a selector, assigning it a value using the property: value syntax. For instance:
:root {
  --primary-color: #3498db;
  --body-font-size: 16px;
  --dark-background-color: #d3d4d5;
}

Using CSS Variable

To use our just created CSS variable in parts of our stylesheet, it is required you reference it using the `var()` function. Here is the syntax for doing this:

body {
  background-color: var(--dark-primary-color);
  font-size: var(--body-font-size);
}

button {
  font-size: var(--body-font-size);
  background-color: var(--primary-color);
}

As seen in the code above, we’ve applied the –primary-color, –body-font-size, and –dark-background-color variables value to the body and button elements. Now we can update these variables in the `: root` selector and the changes propagate throughout every property that uses them.

Let’s consider this example

<!DOCTYPE html>
<head>
  <style>
    :root {
      --primary-color: #3498db;
      --secondary-color: #2ecc71;
      --background-color: #333;
      --font-size: 18px;
    }

    body {
     width: 800px;
     margin: auto;
     text-align: center;
     background-color: var(--background-color);
    }

    h1 {
    color: var(--primary-color);
    }

    button {
    border: none;
    background-color: var(--secondary-color);
    font-size: var(--font-size);
    }
  </style>
</head>
<body>
  <h1>CSS Variables Example</h1>
  <p>Click here to submit</p>
  <button>Submit</button>
</body>
</html>

And here is what my result looks like:

CSS Variables Example
CSS Variables Example

As you can see I set 4 CSS variables (--primary-color: #3498db;,--secondary-color: #2ecc71;,--background-color: #333;,--font-size: 18px;), and we used it to set the background-color, h1 color, button background-color and font-size, and if you noticed the p tag did not have any variable set as its color so it is used the default CSS color which is black.

Cascading and Overriding CSS Variable

I’ve previously mentioned how variables are created in the :root element; however, as I pointed out earlier, they can also be created within an element and used in all its parent elements and children. I find this feature particularly important for achieving a higher level of flexibility in our stylesheets. To override a variable style, I can simply assign a new value to a predefined variable in an element. Let’s consider this example.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      /* Define CSS variables in the :root element */
      :root {
        --primary-color: #7498db;
        --secondary-color: #2ecc71;
        --background-color: #333;
        --font-size: 18px;
      }

      body {
        --primary-color: #3498db;
        width: 800px;
        margin: auto;
        text-align: center;
        background-color: var(--background-color);
      }

      h1 {
        color: var(--primary-color);
      }

      /* Create and use a variable in the 'a' element */
      button {
        border:none;  
        --link-color: #21f34f;
        background-color: var(--link-color);
        text-decoration: none;
      }

      /* Change the 'a' element variable on hover */
      button:hover {
        --link-color: #f44336;
        background-color: var(--link-color);
      }
    </style>
  </head>
  <body>
    <h1>CSS Variables Example</h1>
    <p>Click here to submit</p>
    <button>Submit</button>
  </body>
</html>

In this example, I created variable --primary-color:#7498db in the :root element and I assigned a new value for that same variable name --primary-color: #3498db; and in the button element. and I was able to override the background color of the button when I hover over the button.

Hover effect
Hover effect

CSS Variables Default value.

This is a value that serves as a placeholder in the absence of the Original CSS variable having a value. You can do this by providing a fallback value after the variable name, separated by a comma. Here is an example

:root {
  --primary-color: blue;
}

/* fallback value for primary-color if not defined elsewhere */
.button {
  background-color: var(--primary-color, red);
}

In this example, we define a CSS variable for --primary-color and set its value to blue. In the .button selector, I use the var() function to assign the value of --primary-color to the background-color property. However, we also provide a fallback value of red in case --primary-color is not defined or has no value assigned to it.

So, if we don’t define or assign a value to --primary-color anywhere else in our code, the `.button` element will have a red background color instead of blue.

Creating a light and dark theme using CSS Variables

Let’s put all we have learned to practice and create a theme selector using CSS Variables.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Theming with CSS Variables</title>
    <style>
      :root {
        --primary-color: #4caf50;
        --secondary-color: #ffc107;
        --text-color: #212121;
        --background-color: #ffffff;
      }

      body {
        background-color: var(--background-color);
        color: var(--text-color);
      }

      h1 {
        color: var(--primary-color);
      }

      a {
        color: var(--secondary-color);
      }

      .dark-theme {
        --primary-color: #81c784;
        --secondary-color: #ffd54f;
        --text-color: #f5f5f5;
        --background-color: #424242;
      }
    </style>
  </head>
  <body>
    <h1>Welcome to Soshace</h1>
    <p>
      Soshace is a software development company that specializes in providing
      web development services. We focus on helping clients build full-stack web
      applications using modern technologies, such as React, Angular, Vue.js,
      Node.js, and Python. <a href="#">Read more</a>
    </p>
    <button id="theme-toggler">Toggle Theme</button>

    <script>
      const themeToggler = document.getElementById("theme-toggler");
      const body = document.body;

      themeToggler.addEventListener("click", () => {
        body.classList.toggle("dark-theme");
      });
    </script>
  </body>
</html>

As you can see, I defined the CSS variables in the :root selector, and then I used the CSS variables in my style for my elements. I then created the dark mode by redefining the CSS variables. Next, I used Javascript to handle the toggling of the theme when the change theme button is clicked.
Here is what my result looks like:

Toggling of the theme when the change theme button is clicked
Toggling of the theme when the change theme button is clicked

Browser compatibility for CSS Variables

The majority of contemporary browsers, including Chrome, Firefox, Safari, Edge, and Opera, support CSS variables. However, depending on the browser version, the amount of support may change.

As of September 2021, the following browsers are compatible with CSS variables:

Browser: 49+
Chrome: 31+
Firefox: 9.1+
Edge: 15+
Opera: 36+
For users of Internet Explorer, you must offer fallback styles because IE does not accept CSS variables at all.

It’s best practice to always provide fallback styles for browsers that do not support CSS variables in order to guarantee cross-browser compatibility. You may achieve this by using the var() method to provide the CSS property a fallback value, like in the following example:

Conclusion

In conclusion, CSS variables, usually referred to as custom properties, have fundamentally changed how we approach style for websites. They provide programmers additional freedom, maintainability, and scalability, allowing them to produce designs that are more dynamic and responsive. We can effectively manage and reuse values across all of our stylesheets, simplify theming, and adjust to different user preferences by using CSS variables. As browser support for CSS variables keeps improving, I consider them to be an indispensable tool for contemporary web development, and as the digital world changes, developers will be able to create websites that are more beautiful, effective, and user-friendly by embracing this strong feature.

To learn more about CSS Variables this documentation will help you.

CSS Flexbox

Flexbox, also known as Flexible Box Layout, is a CSS layout module that has transformed the approach to responsive design and content arrangement. Flexbox provides a more efficient and effective method for aligning, distributing, and ordering items within a container. This eliminates the need for us developers to utilize floats, tables, or other less-than-ideal solutions that used to give us grief.

Leave a Reply