CSS Variables (Custom Properties) Guide

📖 7 min read 🏷️ #CSS, #Custom Properties, #Variables, #Beginner
CSS Custom Properties, commonly known as CSS variables, allow you to store reusable values in your stylesheets. They make your CSS more maintainable, enable easy theming, and can be changed dynamically with JavaScript.
1

What Are CSS Variables?

CSS variables are custom properties that hold reusable values throughout your stylesheet. Defined with double dashes (--), they can store colors, font sizes, spacing values, or any CSS value. Example: --primary-color: #3498db;

2

Declaring and Using Variables

Declare variables in the :root selector for global access: :root { --primary: #3498db; --padding: 1rem; }. Use them with the var() function: color: var(--primary); padding: var(--padding);. You can also set fallback values: var(--primary, blue).

3

Theming with CSS Variables

CSS variables make dark/light mode theming incredibly easy. Define color variables in :root for the light theme, then override them in a dark mode class or @media query. Update just the variable value and every usage updates automatically.

4

Dynamic Changes with JavaScript

Unlike preprocessor variables (Sass/LESS), CSS variables can be changed at runtime. Use document.documentElement.style.setProperty("--primary", "#e74c3c") to update values on the fly. This enables live theme switching and interactive design.

5

Scoping and Inheritance

CSS variables respect the cascade. Variables defined in a container only apply within that container and its children. This allows component-level theming. Override a variable in a specific section to create visual variations without duplicating CSS.

6

Practical Use Cases

Use cases include: consistent color palettes across large projects, easy responsive design (change spacing variables at breakpoints), animation parameters (store durations and delays), and design system foundations. CSS variables are supported in all modern browsers.

← Back to All Tutorials