Theme switch
A theme change is a state change, so it should land at once: no smeared fade on switch, and no flash on load.
The problem
Buttons ease their background on hover. Borders ease on focus. Each has its own duration. Flip the theme, and every one of those transitions fires at once at its own speed, so the page washes from light to dark over half a second instead of switching.
The load has the opposite problem. A stylesheet can’t know the saved theme, and a framework finds out too late, so the page paints in the default first and then jumps.
What I concluded
Both come from the browser painting before you meant it to. So turn transitions off for the moment of the flip, and only that moment.
function toggleTheme() {
const root = document.documentElement;
root.classList.add("theme-switching");
root.classList.toggle("dark");
// removed only once the browser has styled the new theme
requestAnimationFrame(() => requestAnimationFrame(() =>
root.classList.remove("theme-switching")));
}
.theme-switching, .theme-switching * {
transition: none !important;
}
One frame isn’t enough. The class has to still be there when styles for the new theme are computed, so it comes off on the frame after.
For load, a few lines run inline in the <head>, before anything draws, read the saved theme and set the class. Inline, because an external script arrives after first paint. Wrapped in try, because storage can throw in private windows.
Rules
- The guard is a moment, not a theme. Hanging it off
.darkwould kill hover easing for as long as the theme is dark. - Hovers are untouched. Two frames later every transition is back.
- The saved theme applies before first paint. Inline, in the head, inside a
try. - Color tokens, not literals. This works because the theme is one class flipping one set of variables. A hardcoded dark color has to be found by hand.
- Reduced motion goes further. Durations go to zero everywhere, permanently.
What you get
The page switches in one frame and loads in the right theme. Easing is for things the person is moving, and nobody is moving the whole page from light to dark.
The demo has a toggle for the guard: turn it off and flip the theme to see the wash. Related: Scroll fades.