Detect if User Is Using Dark Mode

As I use dark mode on all of my devices, all of the time, I wanted to find out how easily I can detect if a user’s device is set to dark mode and serve an alternative stylesheet to these users. As it turns out, it’s actually ridiculously easy with the help of one media query: prefers-color-scheme.

The demo for this tutorial can be found here. If you don’t have a device that includes a dark mode feature, you can see the example on YouTube.

  • CSS
@media (prefers-color-scheme: dark) {}

This query has only two options: light or dark. By default, the light version is served.

If the above media query evaluates to true, the user’s device is set to dark mode, so whatever CSS we pop in here, will be served to devices with dark mode enabled. The possibilities are endless with this power.

Adding some dark mode styles

For my minimal demo page, I just had to change a few elements. Your site may need more 😉

  • CSS
@media (prefers-color-scheme: dark) {
   body { 
      background: #3e3e3d;
   }
   header#primary-header { 
      background: #3e3e3d;
   }
   h2, p {
      color: #fff;
   }
}

There you have it, a super simple way to check if a device has dark mode enabled.

If this tutorial has helped you, I wouldn't say no to a coffee as a tip ☕️

Buy Me a Coffee at ko-fi.com

Leave a Reply

Your email address will not be published. Required fields are marked *