Dark Mode and Theming with Custom Properties
Build accessible light and dark themes with semantic CSS tokens, system preferences, and a user-controlled toggle.
One Theme Model, Many Components
Prerequisites: selectors, the cascade, color values, and CSS custom properties from the previous lesson. The objective is to make a small page follow a visitor's operating-system color preference, allow an explicit override, and keep every component styled through the same semantic tokens.
A theme is not just swapping a black background for a white one. It includes text, borders, surfaces, focus rings, form controls, shadows, and sometimes illustrations. A design token gives each role a stable name; a theme changes the token values, not the component rules.
Name Colors by Their Job, Not Their Appearance
--ink and --paper are descriptive, but names such as --text, --surface, and --border communicate how a value is used. That makes a theme change readable and avoids assumptions that every background is the same color.
:root {
color-scheme: light;
--page: #f8fafc;
--surface: #ffffff;
--text: #172033;
--muted-text: #475569;
--border: #cbd5e1;
--accent: #1457c5;
}
body {
background: var(--page);
color: var(--text);
}
.course-card {
background: var(--surface);
border: 1px solid var(--border);
}
.course-card__summary {
color: var(--muted-text);
}
.course-card a {
color: var(--accent);
}Every component consumes a role, not a particular theme. A dashboard card, progress panel, and navigation bar can all use --surface while the token is changed centrally. Keep an eye on contrast when choosing the two palettes: a color pair that looks distinct is not automatically readable for small text.
Let the Browser Choose When There Is No Saved Override
The prefers-color-scheme media feature exposes the visitor's system preference. Use it as the default rather than guessing. The :root:not([data-theme]) selector is important: it ensures the operating-system rule only applies while the page has no explicit theme attribute.
:root {
color-scheme: light;
--page: #f8fafc;
--surface: #ffffff;
--text: #172033;
--muted-text: #475569;
--border: #cbd5e1;
--accent: #1457c5;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme]) {
color-scheme: dark;
--page: #111827;
--surface: #1f2937;
--text: #f8fafc;
--muted-text: #cbd5e1;
--border: #475569;
--accent: #93c5fd;
}
}The color-scheme property also tells the browser which native control palette to use for elements such as form controls. It does not theme your custom components; those still need to use the tokens.
Give a Visitor's Choice Higher Priority
Explicit attributes on the root element override the automatic palette. Put the declarations after the default values so the intent is easy to find, and keep the same token names in each block.
[data-theme="light"] {
color-scheme: light;
--page: #f8fafc;
--surface: #ffffff;
--text: #172033;
--muted-text: #475569;
--border: #cbd5e1;
--accent: #1457c5;
}
[data-theme="dark"] {
color-scheme: dark;
--page: #111827;
--surface: #1f2937;
--text: #f8fafc;
--muted-text: #cbd5e1;
--border: #475569;
--accent: #93c5fd;
}
:focus-visible {
outline: 3px solid var(--accent);
outline-offset: 3px;
}Because the rules apply to the root element and its descendants inherit custom properties, component CSS stays unchanged. Test focus indicators and error states in both palettes too; theme tokens must not make interaction or status harder to perceive.
Change State Without Rebuilding the Page
Use a real button so keyboard users can operate it without extra event handling. The page can use a stable accessible name and aria-pressed to expose whether dark mode is active. The script below restores only recognized values and leaves the system preference alone when there is no saved choice.
<button id="theme-toggle" type="button" aria-pressed="false">
Dark theme
</button>const root = document.documentElement;
const button = document.querySelector('#theme-toggle');
let savedTheme = null;
try {
savedTheme = localStorage.getItem('theme');
} catch {
// Storage may be unavailable; system preference still works.
}
if (savedTheme === 'light' || savedTheme === 'dark') {
root.dataset.theme = savedTheme;
}
function isDarkTheme() {
if (root.dataset.theme === 'dark') return true;
if (root.dataset.theme === 'light') return false;
return window.matchMedia('(prefers-color-scheme: dark)').matches;
}
function updateButton() {
const isDark = isDarkTheme();
button.setAttribute('aria-pressed', String(isDark));
}
updateButton();
button.addEventListener('click', () => {
const nextTheme = isDarkTheme() ? 'light' : 'dark';
root.dataset.theme = nextTheme;
try {
localStorage.setItem('theme', nextTheme);
} catch {
// The current page still changes even if it cannot be saved.
}
updateButton();
});In production code, guard the query if this script can load on pages without the button. If the saved choice must apply before first paint, initialize it in a small script before the page's styles are painted, and account for your content-security policy. Do not store sensitive data in web storage; a theme preference is low-risk state, not an authentication mechanism.
data-theme="light" in the HTML unconditionally: doing so prevents the system dark-mode rule from applying before JavaScript runs. Leave the attribute absent unless a saved or user-selected override exists.Review the Palette as a Set of Interface States
Review the whole interface, not just its page background
A theme passes only when the whole interface remains usable. Check body text, muted copy, links, keyboard focus, disabled controls, validation messages, charts, and images with transparent backgrounds. Use browser DevTools to inspect computed custom properties and emulate the preferred-color-scheme media setting.
| Check | What to verify | Common issue |
|---|---|---|
| Text contrast | Body and small text remain legible on each surface. | Muted text becomes too faint in dark mode. |
| Interactive states | Focus, hover, pressed, and disabled states are distinguishable. | Focus ring reuses a low-contrast surface color. |
| Native controls | Inputs and menus follow the intended color scheme. | Custom background conflicts with native control colors. |
| Preference behavior | System setting applies until a visitor chooses an override. | A hard-coded attribute masks the media query. |
Do not use color as the only way to communicate meaning. A success message should also say that it succeeded, and an error should have text and an appropriate semantic relationship to its field. Dark mode does not fix a missing label or an inaccessible component.
Theme Bugs That Hide Until Someone Uses the Page
Why it fails: A single component can remain white in dark mode while its neighbors change.
Better approach: Route all reusable colors through semantic tokens and search for remaining literal colors in component CSS.
Why it fails: The media query can overwrite the visitor choice if it uses an equally broad selector or later conflicting declarations.
Better approach: Scope automatic values to :root:not([data-theme]) and define explicit attribute themes separately.
Why it fails: It influences browser-provided controls but does not recolor your own backgrounds, text, or borders.
Better approach: Use custom properties for authored UI and set color-scheme for native controls.
Why it fails: Old or malformed storage values can create an unsupported theme state.
Better approach: Accept only the known values light and dark, and retain the CSS system preference as the fallback.
Build a Theme That Survives Real Use
- Take a page you have already built and replace repeated foreground, surface, border, and accent colors with semantic custom properties.
- Add a system dark preference that applies only when there is no manual theme override.
- Build a keyboard-operable toggle and test it with storage disabled or unavailable.
- Check focus, validation, disabled, and muted states in both palettes. Record any contrast issue and correct the token, not just one component.
- Reload under both operating-system preferences, then choose a theme manually and confirm that the explicit choice persists.
🎯 Key Takeaways
- ✓Semantic custom properties let components consume roles such as --surface and --text rather than hard-coded palette colors.
- ✓Use prefers-color-scheme as the default and scope it so an explicit theme choice takes precedence.
- ✓The color-scheme property helps native controls; custom interface elements still need token-driven styles.
- ✓A real button plus an exposed pressed state makes a theme toggle understandable and keyboard-operable.
- ✓Treat web storage as optional: validate values, handle unavailable storage, and do not store sensitive data there.
- ✓Review contrast, focus, forms, and status messages in both themes; dark mode is an accessibility and design concern, not a color filter.
What comes next
Next, return to motion: use transitions to make state changes feel smooth without sacrificing performance or accessibility.
Lesson 32 → CSS TransitionsHELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
