Skip to content

🌐 Leggi in Italiano

Flash-free dark mode with Tailwind CSS

A few lines of inline script prevent the annoying white flash on load when the user prefers the dark theme.

Alessandro Manias Alessandro Manias Published on · 1 min read
Half light screen and half dark screen with a moon

The problem is well known: the page is shown with the light theme and, a moment later, JavaScript applies the dark theme. The result: an unpleasant flash.

The cause

The component that manages the theme is hydrated after the first paint. Any logic inside onMount arrives too late.

The fix: a blocking script in app.html

An inline script, executed before the body is rendered, reads the saved preference and immediately applies the dark class:

<script>
	const stored = localStorage.getItem('theme');
	const prefersDark = matchMedia('(prefers-color-scheme: dark)').matches;
	if (stored === 'dark' || (!stored && prefersDark)) {
		document.documentElement.classList.add('dark');
	}
</script>

Tailwind in class mode

With darkMode: 'class' the dark: variants are only active when the class is present on the root element. Even the icons of the toggle button can be chosen via CSS, so they are correct from the very first frame.

  1. The script sets the class.
  2. The CSS applies the right colours.
  3. The component hydrates and reads the state that is already there.

© 2026 Wordpress e PHP. Statically generated with SvelteKit.