Cover
Foto profil

Bembi Pramudya

@beemind

Hi! I am Bembi Pramudya, a developer from Indonesia. I spend my free time building software, tinkering with web tools, and exploring frontend design.

DeveloperIndonesiabembee.cc
Web

Dark Mode Done Right: No Theme Flash

Bembi Pramudya
Bembi PramudyaSep 25, 2026 · 4 min read
Dark Mode Done Right: No Theme Flash

Ever opened a dark-mode website only to see it flash white for a split second? That is called flash of wrong theme — the correct theme is applied only after JavaScript finishes loading.

The fix is simple: decide the theme BEFORE the browser paints the page. Put a tiny script directly inside <head>, before CSS loads.

<script>
(function(){
  try {
    var t = localStorage.getItem("theme") || "light";
    document.documentElement.dataset.theme = t;
  } catch(e){}
})();
</script>

This script reads the theme choice from localStorage and stamps it as a data-theme attribute on <html> — all before first paint, so there is zero flashing.

Then in CSS, define variables per theme. Every color on the site references these variables, and switching themes becomes as easy as changing one attribute.

:root { --bg: #0b0b0d; --body: #f2f2f0; }
[data-theme="light"] { --bg: #f4f2ed; --body: #1c1c1a; }
body { background: var(--bg); color: var(--body); }

For "auto" mode, read matchMedia("(prefers-color-scheme: dark)") and listen for changes — so the site follows the phone theme live. Small, but details like this make a website feel premium.