HeadlinesBriefing favicon HeadlinesBriefing.com

Implementing Dark Mode with CSS Meta Tags and JavaScript Toggles

Hacker News •
×

Web developers have long relied on the prefers-color-scheme media query to match a site’s look to the user’s operating‑system theme. That approach, however, leaves users without a way to fine‑tune the experience per site. A sensible fallback is to set a meta tag in the document head that declares the available schemes: `<meta name="color-scheme" content="light dark">` Predictably, the first visit adopts the OS preference.

When users want to override the system default, developers can expose a toggle that writes the chosen value into the same meta tag and persists it in localStorage. Clicking "Light" or "Dark" updates the `content` attribute to `light` or `dark`, while a "System duplicator" restores the original `light dark` fallback. The color-scheme property propagates to system UI elements, gradients, and images that use the `light‑dark()` function.

Despite these tools, a gap remains: the color-scheme setting does not automatically influence the prefers-color-scheme media query, except inside iframes or SVGs where browsers apply the parent value. Safari’s recent additions still lack full compliance, and the spec for overriding the media query via JavaScript is stalled by platform resistance. Developers must therefore rely on style queries or custom properties to adapt shadows, borders, or other non‑color styles.