Skip to content
All articles
Engineering · 1 min read

Dark Mode Without the Flash

A Light/Dark/System toggle that never flashes the wrong theme on load — built with a tiny pre-hydration script, CSS variables and Radix colour scales.

Eijaz
Eijaz
Founder & Writer · Updated Jul 12, 2026
Source code on a dark screen
On this page

The dreaded “flash of the wrong theme” happens when your CSS loads before your JavaScript decides which theme to apply. The fix is to decide before the first paint.

Decide in the head

A tiny inline script in <head> reads the saved preference and sets a class on <html> synchronously — before any content renders:

<script>
  (function () {
    var m = localStorage.getItem('theme') || 'system';
    var d = m === 'dark' ||
      (m === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
    document.documentElement.classList.toggle('dark', d);
  })();
</script>

Two-layer colour tokens

Raw Radix scales live in :root and .dark; semantic tokens reference them. Because the utilities keep the var() reference intact, switching the class re-resolves every colour at runtime — no rebuild, no flash.

Let the system lead

Default to System. Most people have already told their OS what they want; the kindest default is to listen.

Related reading