How to Use CSS Variables Like a Pro

How to Use CSS Variables Like a Pro

CSS variables, also known as custom properties, help you to minimize repetition in your style sheets. This, in turn, helps you save time and effort when making changes to your design. You can also rest assured that you won’t miss any values you need to update.


Access to the DOM allows you to create variables, store them, and reuse them throughout your style sheet.


How to Define and Use CSS Variables

To make your style sheets more arranged, maintainable, and reusable, you can utilize CSS variables in any property that accepts a value.

Take the following example of an HTML file and CSS file that doesn’t use CSS variables.

HTML:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <title>CSS Variables - Button Variations</title>
    <link rel="stylesheet" href="Variables.css" />
  </head>
  <body>
    <div>
      <h1>CSS Variables</h1>
      <div>
        <button class="btn sub-primary">Primary</button>
        <button class="btn">Secondary</button>
      </div>
    </div>
  </body>
</html>

CSS:

 .btn 
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;
  color: red;

This is what your page should look like:

screenshot of two buttons styled color red with CSS

The .btn class used in the above style sheet isn’t dynamic and causes you to create a separate class to customize individual buttons. Creating beautiful websites requires you to be dynamic with your front-end styling. Implementing buttons this way will simply make that task a pain to achieve.

Like most programming languages, You have to initialize and substitute CSS variables.

To initialize a CSS variable, prefix the variable name with double hyphens:

 :root

You can initialize a variable anywhere but note that you will only be able to use that variable inside the initialized selector. Because of this, CSS variables are conventionally initialized inside the root selector. This targets the highest-level element of the DOM and allows the variables to be accessible by the entire HTML document on a global scale.

To substitute the variable into your CSS styling, you will use the var() property:

 :root 
  
  --primary:
  --secondary:

.btn
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;
  color: var(--primary);
  background-color: var(--secondary);

.sub-primary
  color: var(--secondary);
  background-color: var(--primary);

The root selector contains two variables: –primary and –secondary. Both variables are then substituted into the .btn class as a color and background color respectively.

Using the variables, you can style individual elements much more easily. By reusing variables, you can quickly change a value once to update it in every instance.

screenshot of two buttons styled different colors with CSS variables

The var() property can also take a second argument. This argument acts as a fallback value for the first argument in a situation where the first is not defined or is invalid.

For example:

 :root 
  --primary:
  --secondary:

.btn
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;
  color: var(--primary, blue);

In this example, substitute the –primary variable into color style. If for any reason, this value fails, the style sheet will use the second value as a fallback. You can also use another CSS variable as a fallback value.

Manipulating and Overriding CSS Variables With JavaScript

Manipulating CSS variables using JavaScript can be a powerful way to change the look and feel of your website on the fly. Using JavaScript, you can update the values of these variables and see the changes reflected in your site.

It’s important to note that the changes made with JavaScript will only apply to the current session. You must either update the original source or store the new value on the client, like in a cookie, to persist the changes.

Here is an example of how to use JavaScript to update the value of a CSS variable.

HTML:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <title>CSS Variables - Button Variations</title>
    <link rel="stylesheet" href="Variables.css" />
    <script>
    function changeColor()
      
      const myElement = document.querySelector(":root");

      
      let currentValue = getComputedStyle(myElement).getPropertyValue(
        "--secondary"
      );

      // Set the new value for the variable
      myElement.style.setProperty("--secondary"https://www.makeuseof.com/css-variables-how-use-pro/,"#DAF7A6");
    
    </script>
  </head>
  <body>
    <div>
      <h1>CSS Variables</h1>
      <div>
        <button class="btn sub-primary" onclick="changeColor()">
         Primary
       </button>
        <button class="btn">Secondary</button>
      </div>
    </div>
  </body>
</html>

CSS:

 :root 
  --primary:
  --secondary:

.btn
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;

.sub-primary
  color: var(--primary);
  background-color: var(--secondary);

In this JavaScript code, the changeColor() function updates the color of the first button when the user clicks on it.

Using DOM traversal methods, you can access the classes or selectors applied in your HTML document and manipulate the values.

Before clicking the button:

Screenshot of two buttons. One of them styled with CSS variables

After clicking the button:

screenshot of two buttons. One of them styled color white using JavaScript and CSS variables

You can also use JavaScript to create new CSS variables or remove them altogether.

For example:

 // Create a new variable
document.documentElement.style.setProperty('--new-color', 'blue');


document.documentElement.style.removeProperty('--new-color');

Using CSS Variables With Preprocessors

Using variables within frontend technology was initially achieved with CSS preprocessors like SASS, LESS, and Stylus.

The purpose of CSS preprocessors is to develop code that extends the fundamental capabilities of standard CSS. Then have that code compiled into standard CSS for the browser to understand, much like how TypeScript works with JavaScript.

With the development of CSS variables, preprocessors are no longer as important, but they can still offer some use if combined with CSS variables in your project.

You can define a SASS variable $main-color and use it to set the value of a CSS variable. Then, use the CSS variable in a regular style class.

You can also use SASS functions to manipulate the values of CSS variables.

For example:

 :root 
  --primary: $main-color;
  --secondary: lighten(var(--primary), 20%);

.btn
  color: var(--primary);
  background-color: var(--secondary);

Here, the SASS function lighten() manipulates the value of –primary to obtain a value for –secondary.

Note that SASS variables are not accessible by JavaScript. So if you need to manipulate the values of your variables at runtime, you should use CSS variables.

Using CSS variables and preprocessors together, you can take advantage of both benefits, like using powerful preprocessor features like loops and functions and CSS variables feature like CSS cascading.

Tips for Using CSS Variables in Web Development

Here are a few important tips to note that’ll help you utilize CSS variables better.

Start With a Clear Naming Convention

Choose a naming convention for your variables that makes them easy to understand and use. For example, use a prefix such as –color- for color variables or –spacing- for spacing variables.

Use Variables in Media Queries

Use variables in media queries to make it easy to adjust your design for different screen sizes.

Take Advantage of the Cascading Nature of CSS

Remember that CSS variables are cascading, meaning that if you set a variable on a parent element, it will affect all its children.

Use CSS Variables With Caution

Using too many CSS Variables can cause confusion, so use them with caution, and only when it makes sense and improves the maintainability of your code.

Test Your Variables

CSS variables are a unique way to write clear and maintainable code within your style sheet.

It is important to note that they are still not fully supported on all browsers. Hence, you should test your variables for browser compatibility to ensure that they are working as expected and that any fallback values work as you expect them to.