Tutorial 18 of 44 in series
CSS Custom Properties
Use variables in CSS
Abhishek Sharma 2026-05-30 Web Development / Frontend / CSS
Custom Properties
Custom properties (also called CSS variables) let you store reusable values:
Demo: CSS Variables
HTML
<div class="card primary">Primary</div>
<div class="card secondary">Secondary</div>
<div class="card accent">Accent</div> CSS
:root {
--primary: #6366f1;
--secondary: #059669;
--accent: #f59e0b;
--radius: 8px;
--padding: 12px 20px;
}
.card {
color: white;
font-weight: bold;
padding: var(--padding);
margin: 4px 0;
border-radius: var(--radius);
}
.primary { background: var(--primary); }
.secondary { background: var(--secondary); }
.accent { background: var(--accent); }
Live Output Window
Defining Variables
:root {
--main-color: #6366f1;
--font-size: 1.125rem;
}
Using Variables
.element {
color: var(--main-color);
font-size: var(--font-size);
}
Fallback Values
Provide a fallback if the variable is not defined:
Demo: Variable Fallbacks
HTML
<p class="fallback">Color uses fallback if variable is missing</p> CSS
p {
color: var(--undefined-var, #dc2626);
font-size: var(--font-size, 1.25rem);
}
Live Output Window
Variables can be scoped to any selector, not just :root. This enables themes and contextual overrides.
Keep learning
Related tutorials from across the library.
Tutorial
Introduction to CSS
Learn what CSS is and why it matters
Web Development / Frontend / CSS
CSSWeb Development
Tutorial
History of CSS
Understand how CSS evolved
Web Development / Frontend / CSS
CSSWeb Development
Tutorial
Adding CSS
Three ways to add CSS to a page
Web Development / Frontend / CSS
CSSWeb Development