CSS Variables: A Comprehensive Guide

Cascading Style Sheets (CSS) variables, also known as custom properties, have revolutionized how we manage styles in web development. They allow you to define reusable values for properties like colors, fonts, spacing, and more, making your stylesheets more maintainable, dynamic, and easier to work with.

What are CSS Variables?

At their core, CSS variables are custom properties that you define with a name starting with two hyphens (--) and assign a value. These variables can be accessed and used in your CSS rules using the var() function.


:root {
  --primary-color: #007bff;
  --main-font: 'Arial', sans-serif;
}

.button {
  background-color: var(--primary-color);
  color: white;
  font-family: var(--main-font);
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
}
                

Benefits of Using CSS Variables

  • Maintainability: Easily update a value in one place and have it reflected across your entire site.
  • Theming: Dynamically change the theme of your website by altering the values of a few key variables.
  • Readability: Give meaningful names to complex values, making your CSS more understandable.
  • Responsiveness: Use media queries to change variable values based on screen size.
  • JavaScript Integration: Manipulate CSS variables directly with JavaScript for interactive effects.

Scope and Inheritance

CSS variables follow the standard CSS cascade and inheritance rules. You can define variables globally in the :root pseudo-class (which usually refers to the <html> element), or locally within specific selectors.

This is a simple example box.

Let's see how we can redefine a variable for a specific element:


:root {
  --base-spacing: 1rem;
}

.card {
  padding: var(--base-spacing);
  border: 1px solid gray;
}

.special-card {
  --base-spacing: 1.5rem; /* Overrides for this specific element */
  padding: var(--base-spacing);
  background-color: lightblue;
}
                

This card uses a custom color and spacing variable.

Using Variables with JavaScript

JavaScript can easily read and write CSS variables. This is incredibly powerful for creating dynamic UIs.


// Get the root element
const root = document.documentElement;

// Get the value of a CSS variable
const primaryColor = getComputedStyle(root).getPropertyValue('--primary-color');
console.log("Primary color:", primaryColor); // Output: #007bff

// Set the value of a CSS variable
root.style.setProperty('--primary-color', '#ff0000');
                

You can use this to create color pickers, adjust themes on the fly, or animate properties based on user interactions.

Advanced Techniques

Fallbacks for Variables

The var() function accepts an optional second argument, which acts as a fallback value if the variable is not defined.


.element {
  color: var(--undefined-variable, black); /* If --undefined-variable is not set, color will be black */
}
                

Using Variables in Calculations

Variables are particularly useful within CSS calc() functions.


:root {
  --base-padding: 15px;
}

.container {
  width: calc(100% - 2 * var(--base-padding));
  margin: 0 auto;
  padding: 0 var(--base-padding);
}
                

Custom Properties for Design Systems

CSS variables are the backbone of many modern design systems, allowing for consistent theming and component styling across large projects.

This text uses a custom font defined via a variable.

Conclusion

CSS variables are an indispensable tool for modern front-end development. They enhance maintainability, enable powerful theming capabilities, and provide a robust way to integrate dynamic behavior with CSS. By embracing custom properties, you can write cleaner, more organized, and more flexible stylesheets.