CSS Variables
6 min read Quiz at the end
CSS custom properties store reusable values. Define in :root: --primary: #3b82f6. Use with var(--primary). They cascade, inherit, and can be changed by JavaScript at runtime for themes and dynamic UI.
Custom Properties (CSS Variables) :root {
--color-primary: #3b82f6;
--color-text: #111827;
--color-bg: #ffffff;
--spacing-sm: 8px;
--spacing-md: 16px;
--radius: 8px;
--shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.card {
background: var(--color-bg);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: var(--spacing-md);
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
:root {
--color-bg: #111827;
--color-text: #f9fafb;
}
}
Topic Quiz · 5 questions
Test your understanding before moving on
1. CSS variables are declared with:
A. $name
B. --name
C. @name
D. var-name
💡 CSS custom properties (variables) are declared with -- prefix: --primary: blue;
2. Where should global CSS variables go?
A. body
B. :root
C. html
D. *
💡 :root selects the root element — variables here are globally accessible.
3. What is the fallback value syntax?
A. var(--color, default)
B. var(--color || default)
C. var(--color ?? default)
D. var(--color, !default)
💡 var(--color, fallback) uses the fallback if --color is not defined.
4. Can CSS variables be changed with JavaScript?
A. No
B. Yes — document.documentElement.style.setProperty()
C. Only on hover
D. Only in media queries
💡 JavaScript can update CSS variables: document.documentElement.style.setProperty('--color', 'red');
5. CSS variables vs preprocessor variables (Sass $var)?
A. No difference
B. CSS vars are live (update at runtime); Sass vars are compiled away
C. Sass vars are faster
D. CSS vars are not supported
💡 CSS custom properties are live DOM values that can be changed at runtime; Sass vars are static.
Submit answers