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?
A. @media dark
B. @media (color-scheme: dark)
C. @media (prefers-color-scheme: dark)
D. @media theme: dark
💡 @media (prefers-color-scheme: dark) detects the OS-level dark mode preference.
2. Which CSS feature enables both dark/light?
A. color-scheme: auto
B. prefers-color: auto
C. light-dark() function
D. color-auto()
💡 CSS light-dark() applies one value in light mode and another in dark mode.
3. How do you toggle dark mode with JavaScript?
A. document.darkMode = true
B. document.documentElement.classList.toggle('dark')
C. CSS.dark(true)
D. style.dark = true
💡 Toggle a class on <html> and style with [data-theme="dark"] in CSS.
4. CSS variables are ideal for dark mode because:
A. They are faster
B. They update live throughout the entire CSS
C. They are smaller
D. They are cached
💡 Changing CSS variable values in :root instantly updates all elements that use them.
5. Which property tells the browser the supported color scheme?
A. color-scheme: light dark
B. meta theme-color
C. dark-mode: supported
D. prefers: both
💡 color-scheme: light dark tells the browser the page supports both schemes.
Submit answers