CSS dark mode: how do I support it properly?

poze 2 months ago439 gadeen

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?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 2 months ago

1 Repons

6
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 2 months ago

Sign in and verify your email to post an answer.