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.
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.
- The script sets the class.
- The CSS applies the right colours.
- The component hydrates and reads the state that is already there.