Dark Mode and Theming with Custom Properties

Build accessible light and dark themes with semantic CSS tokens, system preferences, and a user-controlled toggle.

Est. 35 min Updated Suggest a fix
// Part 01 — Prerequisites and Objective

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.

🎯 Pro Tip
Start by inventorying the colors and surfaces in your page. If a component uses hard-coded colors everywhere, define the tokens first; otherwise dark mode turns into a fragile search-and-replace exercise.
// Part 02 — Semantic Color Tokens

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.

A compact token set for a learning dashboard
: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.

// Part 03 — Follow the System Preference

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.

Base light theme and system dark preference
: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.

💡 Note
Keep the media query as a preference, not as the only way to switch themes. A visitor may choose a bright workspace at night or need a specific contrast setting regardless of their device setting.
// Part 04 — Explicit Theme Overrides

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.

Manual themes override the media preference
[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.

// Part 05 — An Accessible Theme Toggle

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.

Markup for an operable toggle
<button id="theme-toggle" type="button" aria-pressed="false">
  Dark theme
</button>
Apply a saved choice and persist future toggles
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.

⚠️ Important
Do not set 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.
// Part 06 — Verify Contrast and Theme Behavior

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.

A practical theme review matrix
CheckWhat to verifyCommon issue
Text contrastBody and small text remain legible on each surface.Muted text becomes too faint in dark mode.
Interactive statesFocus, hover, pressed, and disabled states are distinguishable.Focus ring reuses a low-contrast surface color.
Native controlsInputs and menus follow the intended color scheme.Custom background conflicts with native control colors.
Preference behaviorSystem 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.

// Part 07 — Common Mistakes

Theme Bugs That Hide Until Someone Uses the Page

Hard-coding a color inside one component

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.

Applying the system preference after an explicit choice

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.

Treating color-scheme as a complete theme system

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.

Saving every click without validating the stored value

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.

// Part 08 — Practice

Build a Theme That Survives Real Use

  1. Take a page you have already built and replace repeated foreground, surface, border, and accent colors with semantic custom properties.
  2. Add a system dark preference that applies only when there is no manual theme override.
  3. Build a keyboard-operable toggle and test it with storage disabled or unavailable.
  4. Check focus, validation, disabled, and muted states in both palettes. Record any contrast issue and correct the token, not just one component.
  5. Reload under both operating-system preferences, then choose a theme manually and confirm that the explicit choice persists.
📌 Real World Example
A useful review question: if you changed the palette tomorrow, would you edit two theme token blocks or hunt through every component? The first answer signals that the theme boundary is doing its job.

🎯 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 Transitions

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...