CSS Variables — also known as Custom Properties — allow you to store reusable values in one place and use them throughout your stylesheet. They make your CSS cleaner, easier to maintain, and more consistent, especially in large projects.
CSS variables are values you define once and reuse everywhere. They start with two hyphens (--) and are accessed with the var() function.
:root {
--main-color: #3498db;
--font-size: 16px;
}
h1 {
color: var(--main-color);
font-size: var(--font-size);
}
CSS variables are usually defined in the :root selector so they can be accessed globally.
:root {
--primary: #ff6600;
--padding: 20px;
}
.card {
--card-bg: white;
}
button {
background: var(--primary);
padding: var(--padding);
}
color: var(--text-color, black);
CSS variables can be updated using JavaScript — perfect for theme switching.
document.documentElement.style.setProperty('--primary', '#00cc66');
:root {
--bg: white;
--text: black;
}
.dark-mode {
--bg: black;
--text: white;
}
body {
background: var(--bg);
color: var(--text);
}
Switch theme with JS:
document.body.classList.toggle("dark-mode");
Here is a simple table for your page:
| Feature | Description |
|---|---|
--variable-name |
Declares a custom property |
var(--name) |
Retrieves the variable value |
var(--name, fallback) |
Uses fallback if variable is not defined |
:root |
Best place to define global variables |
JavaScript setProperty() |
Update variables dynamically |