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
- There is a nice blog article by Andy Clarke about how to design/adjust your website properly for that dark mode.
- For the just recently released Firefox 67, I've created an add-on called “Dark Website Forcer” that you can use to toggle that setting directly in your browser. Note it has some restrictions on what it can do (see the add-on description), and feel free to urge Mozilla for a better API. Of course it's open-source.
Top comments (8)
The media query is now also supported in Chrome 76. To feature-detect if a browser supports it, you can use this snippet:
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 🔥
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.
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