Photo by Elisabeth Pieringer on Unsplash

Will you join the light or dark side? 🔦

Detecting the browser’s theme with CSS media query prefers-color-scheme

How to automatically apply a default theme to your site based on the user’s color scheme preference

batary
Published in
3 min readJun 20, 2019

--

It’s nice to see so many websites, applications, and OSes allowing users to choose between a light and dark mode for their interface style. Applications can typically detect the color scheme of the OS they’re run on, but what about websites?

What if we could turn on dark mode in our OS, and all the websites we browse to default to dark as well?

The prefers-color-scheme CSS media feature can be used to determine whether the user has requested a specific theme. Possible values for this media feature are:

  • no-preference — there is no known preference.
  • light — the user has requested a light theme.
  • dark — the user has requested a dark theme.

You can view the documentation for prefers-color-scheme and a browser compatibility chart from MDN below.

Browser compatibility

A media query can be used to determine the appropriate styles to apply to your site. Here’s some boiler plate media queries you can copy into your own projects:

/* Apply a default color scheme */
@media (prefers-color-scheme: no-preference) {
}/* Apply a light color scheme */
@media (prefers-color-scheme: light) {
}/* Apply a dark color scheme */
@media (prefers-color-scheme: dark) {
}

And here’s a CSS-only demo that uses a media query to style the page. However, you’ll need to view the demo in a browser that supports the media query to see it work.

We can also use JS to determine the user’s preferred color scheme:

const prefersColorSchemeDark = window.matchMedia('(prefers-color-scheme: dark)');if (prefersColorSchemeDark.matches) {
// Apply a dark color scheme
}

Here’s a pen that uses JS to determine the default color scheme, and also let’s you toggle between light and dark mode.

There are several other new user preference media features (and some other really cool functionality 😎) available in the Media Queries Level 5 spec such as:

  • inverted-colors — is the user using inverted colors?
  • prefers-reduced-motion — does the user want less animation?
  • prefers-reduced-transparency — does the user want less transparency?
  • prefers-contrast — does the user want low or high contrast?
  • And the ability to define custom media features! 🙌

It’s amazing to see web standards grow, and there are a lot of other new features being implemented by browsers like the CSS backdrop-filter property and native lazy loading for the HTMLimg and iframe tags.

🦄 What new web standards are you excited for? 🎉

--

--