CSS variables (officially called Custom Properties) are a powerful tool for storing and reusing values in CSS. Unlike variables in preprocessor languages like SASS or LESS, CSS variables are part of the DOM and can be changed in real time with JavaScript or used to create dynamic themes (e.g., switching between light and dark theme).
Variables are defined with the -- prefix (e.g., --primary-color) and used with the
var() function. They enable centralized management of colors, font sizes, spacing, and other values,
which drastically simplifies maintenance of large websites.
The example above shows how CSS variables enable dynamic styling of a website. By clicking buttons, you can switch between themes, change colors and spacing in real time – without reloading the page. All changes happen through simple replacement of variable values in the document root.
| Property/Function | Example | Description |
|---|---|---|
| Defining | ||
--variable-name | :root { --primary: #3498db; } |
Defines a variable (starts with two hyphens) |
Global | :root { --spacing: 10px; } |
Defining in :root allows access from the entire document |
Local | .card { --bg: white; } |
Defining within a specific element (accessible only to it and its children) |
| Using | ||
var() | color: var(--primary); |
Retrieves the value of a variable |
var() with fallback | color: var(--primary, red); |
Retrieves the value; if it does not exist, uses the fallback value (red) |
| Dynamic Changes | ||
JavaScript | document.documentElement.style.setProperty("--primary", "green"); |
Changing a variable value with JavaScript in real time |
Media Queries | @media (prefers-color-scheme: dark) { :root { --bg: #333; } } |
Changing values based on system settings (e.g., Dark Mode) |
Hover/Focus | a:hover { --color: blue; } |
Changing values on user interaction |