Phase 4 — Responsive & Modern
#14 CSS variables
--custom-properties, var(), theming
CSS custom properties
CSS variables (custom properties) let you define reusable values. They start with -- and are accessed with var():
Defining and using variables
:root {
--color-primary: #3b82f6;
--color-text: #1a1a2e;
--color-muted: #6b6b85;
--spacing-sm: 8px;
--spacing-md: 16px;
--spacing-lg: 32px;
--radius: 8px;
}
.card {
color: var(--color-text);
padding: var(--spacing-lg);
border-radius: var(--radius);
border: 1px solid var(--color-muted);
}Theming with variables
Dark mode theme
:root {
--bg: #ffffff;
--text: #1a1a2e;
--card-bg: #f8f7f4;
--border: #e0dbd4;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f0f1a;
--text: #e0e0f0;
--card-bg: #1a1a2e;
--border: #3a3a5e;
}
}
body {
background: var(--bg);
color: var(--text);
}
.card {
background: var(--card-bg);
border-color: var(--border);
}Scope and inheritance
Variables are inherited by child elements and can be overridden locally:
Scoped variables
.section-blue {
--accent: #3b82f6;
}
.section-green {
--accent: #10b981;
}
/* Both sections use --accent, but the value differs */
.section-blue .button,
.section-green .button {
background: var(--accent);
}Fallback values
Fallback
/* If --accent is not defined, use #3b82f6 */
color: var(--accent, #3b82f6);
/* Nested fallback */
color: var(--brand-color, var(--color-primary, blue));Your turn
Try the CSS variable commands below:
terminal — browser