CSS Custom Properties (CSS Variables)
CSS Custom Properties commonly called CSS Variables are one of the most powerful modern CSS features. They reduce repetition, improve maintainability, and unlike preprocessor variables (Sass, Less), they can be changed at runtime with JavaScript.
Why CSS Variables Matter
- Centralize values → Define once, reuse everywhere.
- Dynamic updates → Change values with JavaScript or inline styles.
- Cascading scope → Variables follow normal CSS inheritance rules.
- Responsive design → Use variables inside media queries.
- Math support → Combine with
calc()for dynamic calculations.
Defining and Using Variables
Variables are defined with two dashes (--) and accessed with var().
Code Block Loading...
:root→ defines global variables available everywhere.var(--name)→ retrieves the variable value.- Variables can hold any valid CSS value (colors, lengths, gradients, etc.).
Scope and Reassignment
Variables can be defined at any level. Scope follows CSS inheritance:
Code Block Loading...
- Outside
.container→--primary-coloris yellow. - Inside
.container→--primary-coloris blue.
You can even define variables inline in HTML:
Code Block Loading...
Interacting with Variables via JavaScript
Unlike Sass/Less, CSS variables can be read and updated dynamically:
Code Block Loading...
Math and Fallbacks
- Use
calc()inside variables:
Code Block Loading...
- Provide fallback values:
Code Block Loading...
If --default-margin isn’t defined, 30px is used.