A dark mode toggle that doesn’t flash

The classic dark mode bug is a white flash on every page load. The fix is a tiny script in the head.

Design tokens first

Utility classes and the cascade are not enemies. Utilities handle layout; a handful of element styles handle the prose that editors write.

try {
  const stored = localStorage.getItem('theme');
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  if (stored === 'dark' || (stored === null && prefersDark)) {
    document.documentElement.classList.add('dark');
  }
} catch (error) {
  // Storage can be blocked; the light theme is a safe default.
}

Container queries let the card component decide its own layout, so it looks right in a sidebar and in a three-column grid without extra classes. The snippet above is the whole thing; the version in our repository only adds tests.

Checking it in the browser

  • Define tokens for space, colour, and type
  • Style prose elements once, globally
  • Use container queries for reusable components
  • Check contrast in light and dark mode

Leave a comment

Your email address will not be published. Required fields are marked *