Reading the system preference
Modern operating systems let users choose a light or dark appearance. The browser exposes that choice through the prefers color scheme media feature.
- Wrap rules in a media query for prefers color scheme dark to apply dark styling automatically.
- Pair it with CSS custom properties so a single block of overrides flips the whole palette.
- Declaring the color scheme property tells the browser to also theme native widgets like scrollbars and form controls.
Adding a manual toggle
System preference is a good default, but many apps offer an explicit switch. The common pattern stores the choice and applies a data attribute or class on the root.
- Use the media query as the default.
- Let a stored user choice override the system value.
- Read the preference in JavaScript with matchMedia and listen for changes so the UI updates when the OS theme switches mid session.
Start from the system signal, then allow an explicit override for full control.
Key idea
The prefers color scheme media query reflects the OS theme, and a stored user toggle can override it for an explicit choice.