Auto Dark Mode with CSS

If you want your site to automatically switch between light and dark themes based on the visitor’s system settings, you can use a @media query and the prefers-color-scheme feature.

```css :root { –color-background: #eee; –color-text: #000; }

@media (prefers-color-scheme: dark) { :root { –color-background: #333; –color-text: #eee; } }

body { color: var(–color-text); background-color: var(–color-background); }

```

Updated January 2, 2024 to use :root pseudo-class.


Date
January 1, 2024
Tags
Notes
Kudos
Buy me a Coffee
Support this site.