Dark mode with light-dark(), and a toggle that doesn't flash
Dark mode for my SvelteKit portfolio. Theme colors live in tokens.css using color-scheme and light-dark(), and a toggle overrides the OS setting.

Because my components only use semantic tokens, dark mode didn't require changing any component. The whole change was in tokens.css.
The old way
The usual approach is to write every token twice:
:root {
--text-1: var(--gray-8);
}
@media (prefers-color-scheme: dark) {
:root {
--text-1: var(--gray-1);
}
}It works, but each token's light and dark values end up far apart in the file. Adding a manual toggle on top means writing the dark values a third time.
color-scheme + light-dark()
:root {
color-scheme: light dark;
--brand: light-dark(var(--blue-9), var(--blue-4));
--text-1: light-dark(var(--gray-9), var(--gray-1));
--surface-1: light-dark(var(--gray-0), var(--gray-11));
}
:root[data-theme='light'] {
color-scheme: light;
}
:root[data-theme='dark'] {
color-scheme: dark;
}color-scheme: light darktells the browser the page supports both themes and should follow the OS. It also switches the browser's own UI, such as scrollbars, form controls and the default background.light-dark(a, b)returnsain a light color scheme andbin a dark one. Each token keeps both of its values on one line.[data-theme]forces a theme. With no attribute the site follows the OS. A toggle just sets the attribute on<html>. (Later these selectors lost their:root, and the tokens are declared on any[data-theme]element, so part of a page can force a theme too. My contrast checker post tells why.)
The dark values are the same scales flipped. The brand color moves from --blue-9 to --blue-4, because a dark blue is unreadable on a dark background.
What the build did
The built CSS doesn't contain light-dark(). Lightning CSS, Vite's minifier, replaced it with a fallback for older browsers: two switch variables and a generated @media (prefers-color-scheme: dark) block. My [data-theme] selectors are more specific than that generated :root, so a forced theme still wins over the OS. I write the modern syntax and the build handles older browsers.
Testing
In DevTools, open the command menu (Ctrl+Shift+P), run "Emulate CSS prefers-color-scheme: dark", then add data-theme="light" to <html> in the Elements panel. The page should go back to light even though the OS emulation is still dark.
Avoiding the flash
Saving the choice is easy. Applying it at the right moment is the hard part.
My site is prerendered, so the HTML is generated at build time, when there's no visitor and no localStorage. The browser paints that HTML first, without any data-theme, so it shows the OS theme. Then SvelteKit's JavaScript loads, reads the saved choice, and switches. If you picked dark on a light OS, you'd see a white page flash on every load.
The fix is a small inline script at the top of app.html:
<script>
try {
const theme = localStorage.getItem('theme');
if (theme === 'light' || theme === 'dark') document.documentElement.dataset.theme = theme;
} catch {}
</script>- A plain inline
<script>in<head>blocks parsing. The browser runs it before it reaches<body>, so the attribute is set before anything is painted. SvelteKit's own scripts are modules, which run after parsing, and that's too late. - It validates the value.
localStorageis data from outside your code, and anyone can putbananain it. - The
tryis there becauselocalStoragecan throw when storage is blocked. If it throws, the site just follows the OS.
The toggle
<script lang="ts">
import { onMount } from 'svelte';
type Theme = 'light' | 'dark';
let theme = $state<Theme>();
const systemTheme = (): Theme =>
matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
onMount(() => {
const sync = () => {
const saved = document.documentElement.dataset.theme;
theme = saved === 'light' || saved === 'dark' ? saved : systemTheme();
};
sync();
const query = matchMedia('(prefers-color-scheme: dark)');
query.addEventListener('change', sync);
return () => query.removeEventListener('change', sync);
});
function toggle() {
theme = theme === 'dark' ? 'light' : 'dark';
const root = document.documentElement;
try {
if (theme === systemTheme()) {
delete root.dataset.theme;
localStorage.removeItem('theme');
} else {
root.dataset.theme = theme;
localStorage.setItem('theme', theme);
}
} catch {}
}
</script>
<button
type="button"
onclick={toggle}
aria-pressed={theme ? theme === 'dark' : undefined}
disabled={!theme}
>
Dark theme
</button>themestarts asundefined. During prerendering nobody knows the visitor's theme, so the HTML must not claim one. That's whyaria-pressedisundefineduntil then: Svelte rendersfalseon anaria-*attribute as the string"false", which would tell dark-OS visitors the dark theme is off. Onlyundefinedleaves the attribute out. The button stays disabled untilonMount, which only runs in the browser.- The inline script decides the colors.
onMountonly syncs the button with the attribute the script already set, or with the OS setting if there's no saved choice. Thechangelistener re-syncs it if the OS theme changes while the page is open, andonMountreturns a cleanup function that removes the listener. toggle()either saves an override or removes it. If the new theme differs from the OS, it sets the attribute and saves it. If it matches the OS, it deletes both, so the site goes back to following the system. More on that below.
A fixed label with aria-pressed
The button always says "Dark theme", and aria-pressed tells screen readers whether it's on. A label that flips between "Light" and "Dark" is ambiguous: does it describe the current theme or what happens when you click? This matters for more people than you might think. Many screen reader users have low vision and do care about themes, and voice control users click buttons by saying their label.
Later the button became an animated sun/moon icon (see the follow-up post). The fixed label stayed: it moved into aria-label="Dark theme", plus a title so mouse users get it as a tooltip.
Two states or three?
There was a lively debate about this in 2026. Lea Verou argues that a visible toggle only needs two states, and later that most sites don't need one at all. Bramus makes the case for showing all three (system, light, dark). And Kilian Valkhof's older post points out that a toggle with no way back to "system" is broken.
I went with Lea's model. There's one button, and its two states are the system theme and its opposite. The model underneath still has three states (system, light, dark), but the user never has to choose "system" explicitly. When you click back to the theme that matches your OS, the toggle deletes the override instead of saving it, and the site follows the OS again. If the site ever gets a settings panel, an explicit "Use system setting" option can go there.