DEV Community

rugk
rugk

Posted on

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

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

Top comments (8)

Collapse
 
tomayac profile image
Thomas Steiner

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');
}
Collapse
 
kumareth profile image
Kumar Abhirup

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

Collapse
 
rugk profile image
rugk

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.

Collapse
 
kumareth profile image
Kumar Abhirup

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

Collapse
 
qcgm1978 profile image
Youth

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

Collapse
 
rugk profile image
rugk

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…

Collapse
 
qcgm1978 profile image
Youth

Maybe the chrome doesn't work.

Collapse
 
peke314 profile image
Victor Janin

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