📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials CSS Mastery CSS Variables

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:
💡 CSS custom properties (variables) are declared with -- prefix: --primary: blue;
2. Where should global CSS variables go?
💡 :root selects the root element — variables here are globally accessible.
3. What is the fallback value syntax?
💡 var(--color, fallback) uses the fallback if --color is not defined.
4. Can CSS variables be changed with JavaScript?
💡 JavaScript can update CSS variables: document.documentElement.style.setProperty('--color', 'red');
5. CSS variables vs preprocessor variables (Sass $var)?
💡 CSS custom properties are live DOM values that can be changed at runtime; Sass vars are static.