Introduction
CSS Variables (Custom Properties) allow dynamic styling, theme switching, component reuse, and cleaner maintainability. They're the backbone of modern design systems, dark modes, and responsive styling.
1. Declaring Variables
:root {
--primary: #64b5f6;
--text: #e0e0e0;
}
2. Using Variables
button {
color: var(--text);
background: var(--primary);
}
3. Variable Scoping
Variables cascade, meaning child elements can override parent values.
:root {
--color: white;
}
.card {
--color: red;
}
.card p {
color: var(--color); /* red */
}
4. Fallback Values
color: var(--does-not-exist, #fff);
5. Dynamic Theme Switching
:root {
--bg: #ffffff;
--text: #000000;
}
.dark {
--bg: #121212;
--text: #e0e0e0;
}
Usage:
document.body.classList.add("dark");
6. Variables in Media Queries
:root {
--size: 20px;
}
@media (max-width: 600px) {
:root {
--size: 14px;
}
}
h1 {
font-size: var(--size);
}
7. Variables Inside Components
.card {
--radius: 12px;
border-radius: var(--radius);
}
8. Variables for Transitions
:root {
--speed: 0.3s;
}
button {
transition: background var(--speed);
}
9. Calculation with Variables
:root {
--base: 10px;
}
.box {
padding: calc(var(--base) * 2);
}
10. Inheriting Variables
.parent {
--gap: 10px;
}
.child {
margin-bottom: var(--gap);
}
11. Variables in JS
// read
const val = getComputedStyle(document.documentElement)
.getPropertyValue("--primary");
// write
document.documentElement.style.setProperty("--primary", "#ff0000");
12. Real Example – Light/Dark Mode Toggle
:root {
--bg: #fff;
--text: #000;
}
body.dark {
--bg: #121212;
--text: #e0e0e0;
}
body {
background: var(--bg);
color: var(--text);
}
13. Summary
- Variables create themeable, reusable styles
- They cascade and inherit through DOM
- Use fallback values for safety
- Perfect for dark-mode, spacing systems, responsive scaling
- JS can modify variables at runtime for dynamic UIs