loading...

DYK your website can get a dark mode toggled by your operating system?

rugk profile image rugk ・2 min read

Your website can have a light and dark mode that is automatically toggled by your operation system (OS) or browser.

Making your website dark

Here is the trick: You can use the new prefers-color-scheme media query feature, specified in the Media Queries Level 5.

You simply include a CSS like this:

@media (prefers-color-scheme: dark) {
  body {
    background: #333;
    color: white;
  }
}

This would e.g. just do some simple CSS changes on the colors on your body.

Via JavaScript?

You can also request the status of this property (just like any other media query) with .matchMedia(). This e.g. returns the status:

> window.matchMedia("(prefers-color-scheme: dark)").matches
false

(In this example, the dark mode would be disabled.)

There is a catch, is not there?

Yes, as with many good things, there are some restrictions here…

This feature is only supported by Safari 12.1 and Firefox 67, but I guess browser support will grow, as it is standardized.

Tips

Posted on by:

Discussion

pic
Editor guide
 

The media query is now also supported in Chrome 76. To feature-detect if a browser supports it, you can use this snippet:

if (window.matchMedia('(prefers-color-scheme)').media !== 'not all') {
  console.log('🎉 Dark mode is supported');
}
 

It seems not work in embed iframe such as codepen codepen.io/qcgm1978/pen/gJoOQR

 

I've tried your codepen with Firefox 67 and it worked both with the dark system setting and with my add-on. So I cannot reproduce the problem here…

 

Maybe the chrome doesn't work.

 

Just tried it, but didn't work on Safari as said. Am I missing something? 🤔

 

As per caniuse you need Safari v12.1. Also, did you set your system setting to dark?

See webkit.org/blog/8840/dark-mode-sup... for more information, if that helps.

 

I am on the latest Safari, and my system is always in dark 🔥

 

I did a small video about it not so long ago, it will be fun to play with this with web-apps!
Hope it can help,
youtube.com/watch?v=qG6osW_oyZU