Skip to content

Engineering

Implementing Dark Mode the Right Way

6 min read
Developer focused at work on a laptop

Dark mode is no longer a trend — it’s a standard. But most implementations get it wrong. They invert colors, slap dark: prefixes on every class, and hope for the best. The result: a dark theme that looks like an accident.

The problem with inversion

The naive approach — white becomes black, black becomes white — breaks down in practice. Colors carry different perceptual weights. A saturated blue on a white background works. That same blue on a black background glares.

Shadows that create depth in light mode disappear entirely in dark mode. Borders that were meant to subtly separate become invisible or overpowering.

Semantic tokens as the solution

The key is abstraction. Instead of writing bg-white dark:bg-gray-900, you use bg-background. The token knows what it needs to be in every context:

:root {
  --background: 0 0% 98%;
  --muted: 0 0% 93%;
  --border: 0 0% 87%;
}

.dark {
  --background: 0 0% 5.9%;
  --muted: 0 0% 12%;
  --border: 0 0% 18%;
}

One change, two modes, zero extra classes in components.

Preventing FOUC

Flash of Unstyled Content on load is the most common dark mode bug. The fix: a synchronous script in the <head> that sets the class before the body renders:

<script>
  const theme = localStorage.getItem('theme')
    ?? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
  document.documentElement.classList.toggle('dark', theme === 'dark');
</script>

No flash, no race condition, works with and without JavaScript.

Checking contrast

WCAG 2.1 AA requires 4.5:1 contrast for regular text and 3:1 for large text. In dark mode this is harder to achieve because eyes are more sensitive to bright elements on a dark background.

Our rule: --muted-foreground has at least 5:1 contrast against --background in both modes. Not because the spec demands it, but because readability is non-negotiable.

Conclusion

Dark mode is not a skin — it’s a standalone color system that deserves the same care as the light theme. With semantic tokens you define the intent once and let the system handle the rest.