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

Dark Mode

5 min read Quiz at the end
Support dark mode with @media (prefers-color-scheme: dark). Use CSS custom properties for colours so you only update variables. Toggle themes manually with a data-theme attribute changed by JavaScript.

Dark Mode

/* System preference */
@media (prefers-color-scheme: dark) {
    :root {
        --bg:   #0f172a;
        --text: #f1f5f9;
        --card: #1e293b;
    }
}

/* Manual toggle (add class to html) */
[data-theme="dark"] {
    --bg:   #0f172a;
    --text: #f1f5f9;
}

body {
    background: var(--bg, white);
    color: var(--text, black);
}
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which media query detects dark mode preference?
💡 @media (prefers-color-scheme: dark) detects the OS-level dark mode preference.
2. Which CSS feature enables both dark/light?
💡 CSS light-dark() applies one value in light mode and another in dark mode.
3. How do you toggle dark mode with JavaScript?
💡 Toggle a class on <html> and style with [data-theme="dark"] in CSS.
4. CSS variables are ideal for dark mode because:
💡 Changing CSS variable values in :root instantly updates all elements that use them.
5. Which property tells the browser the supported color scheme?
💡 color-scheme: light dark tells the browser the page supports both schemes.