CSS dark mode: how do I support it properly?

posée 2 months ago442 vuesen

6

I want my site to follow the OS dark mode setting, and also let users override it with a toggle. What's the clean way?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 2 months ago

1 réponse

6
✓
✓ Réponse acceptée

Use CSS custom properties for colors, with three sources of truth in order: the user's explicit choice, then the OS preference, then the default.

:root {
  color-scheme: light dark;
  --bg: #ffffff;
  --fg: #111827;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) { --bg: #0b1020; --fg: #e5e7eb; }
}
:root[data-theme="dark"] { --bg: #0b1020; --fg: #e5e7eb; }

body { background: var(--bg); color: var(--fg); }

The toggle sets document.documentElement.dataset.theme = 'dark' | 'light' (or removes it to follow the system) and saves the choice in localStorage.

Avoid the flash of the wrong theme: apply the saved theme with a tiny inline <script> in <head>, before the CSS paints.

color-scheme makes native form controls and scrollbars match. In Tailwind v4, configure the dark: variant to follow the data-theme attribute so both systems agree.

Connectez-vous pour dire si ça a marché.

answered 2 months ago

Sign in and verify your email to post an answer.