Topic 15 of 30
Variables
Overview
CSS custom properties (--variables) allow you to define reusable values in one place and reference them throughout your stylesheet. They are dynamic (changeable with JavaScript) and cascade like any other CSS property.
Syntax
css
/* Define in :root for global scope */
:root {
--color-primary: #FFD700;
--color-bg: #0f0f0f;
--spacing-md: 16px;
--radius-lg: 12px;
--font-heading: 'Inter', sans-serif;
}
/* Use with var() */
.button {
background: var(--color-primary);
padding: var(--spacing-md);
border-radius: var(--radius-lg);
}
/* Fallback value */
color: var(--color-accent, #FFD700);
/* Change with JavaScript */
document.documentElement.style.setProperty('--color-primary', '#FF6B6B');Common Pitfalls
- CSS variables are case-sensitive: --Color-Primary and --color-primary are different variables.
- Custom properties CAN be changed with JavaScript at runtime — unlike Sass variables which are compiled away.
- Interview tip: var(--x, fallback) fallback only triggers if --x is undefined, NOT if it's set to an invalid value.
Real-World Example
A theme switcher using CSS custom properties:
example
css
/* Light theme (default) */
:root {
--bg: hsl(0, 0%, 98%);
--surface: hsl(0, 0%, 94%);
--text: hsl(0, 0%, 10%);
--primary: hsl(51, 100%, 45%);
}
/* Dark theme */
[data-theme="dark"] {
--bg: hsl(0, 0%, 6%);
--surface: hsl(0, 0%, 12%);
--text: hsl(0, 0%, 95%);
--primary: hsl(51, 100%, 50%);
}
body {
background: var(--bg);
color: var(--text);
}
/* JS: toggle theme */
// document.documentElement.setAttribute('data-theme', 'dark');