CSS Variables
Reusable values with custom properties โ dry, maintainable, themeable CSS.
CSS variables (custom properties) let you store values and reuse them throughout your stylesheet. Change one value, updates everywhere. Like secret masala in Hyderabadi biryani โ once you have the recipe, you can use it everywhere.
:root { --primary: #f97316; --bg: #fff7ed; --radius: 8px; }
.card { background: var(--bg); border-radius: var(--radius); color: var(--primary); }Variables are defined with -- prefix and scoped to the element they're declared on:
:root { /* Global variables โ available everywhere */
--primary: #f97316;
--text: #1e293b;
--bg: #ffffff;
--shadow: 0 4px 6px rgba(0,0,0,0.1);
--radius: 12px;
--gap: 1.5rem;
}
.card { /* Scoped to .card and its children */
--card-bg: #f8fafc;
--card-padding: 1.5rem;
background: var(--card-bg);
padding: var(--card-padding);
}
/* Theme scoping */
[data-theme="dark"] { --bg: #1e293b; --text: #f1f5f9; }Use var() function to access variable values. You can provide fallback values:
/* Basic usage */
.box { background: var(--primary); }
/* With fallback โ if --primary not defined, uses #000 */
.box { background: var(--primary, #000); }
/* Nested fallback โ provide multiple fallbacks */
.box { background: var(--primary, var(--secondary, #000)); }
/* In shorthand properties */
.card { background: var(--bg, white) var(--bg-img, none) center/cover no-repeat; }
/* With calc() */
.box { width: calc(100% - var(--gap, 1rem) * 2); }Real-world variable patterns:
/* Theme switcher โ works with JavaScript */
:root { --bg: #fff; --text: #000; --accent: #f97316; }
[data-theme="dark"] { --bg: #0f172a; --text: #e2e8f0; --accent: #fbbf24; }
body { background: var(--bg); color: var(--text); }
/* Component scoped variables */
.card { --padding: 1rem; --shadow: 0 2px 4px rgba(0,0,0,0.1); padding: var(--padding); box-shadow: var(--shadow); }
.card.featured { --padding: 2rem; --shadow: 0 4px 12px rgba(0,0,0,0.15); }
/* Animation timing */
:root { --duration: 300ms; --easing: ease-in-out; }
.box { transition: transform var(--duration) var(--easing); }
/* JavaScript access */
// document.documentElement.style.setProperty('--primary', '#3b82f6');Practice CSS variables below.
Try these experiments:
Done โ Key Points:
- โ
CSS variables defined with
--prefix, accessed withvar(). - โ
:rootfor global variables. Element scope for local overrides. - โ
var(name, fallback)provides default if variable is not defined. - โ
Theme switching: change variable values in
[data-theme="dark"], everything updates. - โ
JavaScript access:
getComputedStyle+setPropertyfor dynamic changes.
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login