CSS variables explained for beginners
Source: Dev.to
Introduction
When writing CSS, you often repeat the same colors, font sizes, or spacing values again and again. This repetition makes your code harder to maintain. CSS variables (also called CSS custom properties) solve this problem by allowing you to store values in one place and reuse them throughout your stylesheet.
This guide explains CSS variables step by step, using very simple examples suitable for absolute beginners.
What Are CSS Variables?
CSS variables are reusable values defined in CSS.
--main-color: blue;
Here, --main-color stores the value blue.
Why Use CSS Variables?
CSS variables make your code:
- Easier to read
- Faster to update
- More consistent
- Better for large projects
If you change a value in one place, it updates everywhere.
How to Define CSS Variables
Using the :root Selector
The :root selector is the most common and recommended approach for defining global variables.
:root {
--primary-color: #3498db;
--spacing-unit: 1rem;
}
The browser replaces the variable with its stored value wherever it is used.
Local (Scoped) CSS Variables
Variables can also be defined inside a specific selector, limiting their scope.
.card {
--card-bg: #fff;
background-color: var(--card-bg);
}
This variable only works inside .card.
Using Fallback Values
You can provide a fallback value in case the variable is missing.
color: var(--secondary-color, black);
If --secondary-color is not defined, the text will fall back to black.
Common Use Cases for CSS Variables
- Theme colors (light / dark mode)
- Font sizes
- Spacing values
- Reusable layout dimensions
- Design systems
Beginner Mistakes to Avoid
- Forgetting the leading
--when defining variables. - Using variables without the
var()function. - Defining too many unnecessary variables.
- Not using
:rootfor global values.
Conclusion
CSS variables are a powerful yet beginner‑friendly feature that helps you write cleaner, smarter, and more maintainable CSS. By centralising values, you reduce repetition and make future updates a breeze.