I'm writing a personal website on my own but running into an issue that I hardly fixed for a long time:
There is always a flash of light background in the dark mode (FOUC maybe?). Here are the related sources:
This is part of my Tailwind CSS v4 index.css file.
@import 'tailwindcss';
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--color-bgprimary: var(--color-zinc-50);
--color-bgsecondary: var(--color-gray-200);
--color-primary: var(--color-zinc-800);
--color-secondary: var(--color-violet-800);
}
/* Dark mode overrides */
.dark {
--color-bgprimary: var(--color-neutral-900);
--color-bgsecondary: var(--color-gray-700);
--color-primary: var(--color-zinc-200);
--color-secondary: var(--color-cyan-400);
}
This is my Applayout like the entire app entry component. The util-transition-colors is just a utility for transition-colors duration-300 ease-in-out. It still doesn't work if I remove the related transition classes.
}>
I also have the script to set up the initial dark mode in the index.html like below:
This is my dark mode switch logic:
useEffect(() => {
const root = document.documentElement;
const applyTheme = () => {
const systemPrefersDark = isSystemDarkMode();
const currentTheme = theme === 'system' ? (systemPrefersDark ? 'dark' : 'light') : theme;
if (currentTheme === 'dark') {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
};
applyTheme();
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
if (theme === 'system') {
applyTheme();
}
};
mediaQuery.addEventListener('change', handleChange);
return () => {
mediaQuery.removeEventListener('change', handleChange);
};
}, [theme]);
Despite the above, the problem still exists. It is kind of disturbing me while I tried many ways to solve it.
It's my first time asking a question on Stack Overflow. I would appreciate it if anyone could help me. Thanks for reading! :)