Skip to content
Search

CSS:prefers-color-scheme

lastmod 2025-03-10created 2021-06-238 edits

The prefers-color-scheme CSS media feature is used to detect whether the user's system uses a light theme or a dark theme.

Dark Mode Tricks

CSS Custom Properties may be useful

This reminds me of an excellent post by Marcin Wichary where he explores a similar technique and goes one step further by adding all sorts of filters to make sure they have a much higher contrast.

html {
  --text-color-normal: #0a244d;
  --text-color-light: #8cabd9;
}

html[data-theme='dark'] {
  --text-color-normal: hsl(210, 10%, 62%);
  --text-color-light: hsl(210, 15%, 35%);
  --text-color-richer: hsl(210, 50%, 72%);
  --text-color-highlight: hsl(25, 70%, 45%);
}

Dark mode by default

Remember you can reverse it and go dark by default but change to a light theme if a user specifically wants it:

body {
  background-color: black;
  color: white;
}
@media screen and (prefers-color-scheme: light) {
  body {
    background-color: white;
    color: black;
  }
}

Injecting an html class (old style)

  const [darkMode, setDarkMode] = useRecoilState(darkModeState);

  useEffect(() => {
    if (darkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [darkMode]);

See also

Favorite site

author Zer0 sitemap