Create Auto Dark Mode Website with prefers-color-scheme
As we have mentioned in previous post. Dark mode is one of the upcoming web design trend in 2020. So in this tutorial, we’re show you how to make your website switch to dark mode automatically using only CSS Ready? Let’s check it out.
prefers-color-scheme
A new CSS media query feature. prefers-color-scheme will detect the current operation system color setting and enable set of CSS rules accordingly (see MDN). Basically it’s very similar to how we use min-width and max-width to detect device screen size.
So here is my website running on local server. Currently it has light color scheme.
I’m going to make it change the header and body background to grey and the header texts to white on dark mode. These are current related CSS rules.
.site-content, body { background: #f9f9f9; } .site-header { background: #fff; } .site-title a:link, .site-title a:visited { color: #373737; } .header-social-icons .social-icons-menu li a { color: #373737; }
First let’s define prefers-color-scheme for our light theme.
@media (prefers-color-scheme: light) { .site-title a:link, .site-title a:visited, .header-social-icons .social-icons-menu li a { color: #373737; } .site-content, body { background: #f9f9f9; } .site-header { background: #fff; } }
Now you won’t see any change because we’re using same colors with the original. But if you open the inspector, you’ll see that the our new CSS is now working.
Auto Switch to Dark Mode
Next let’s define colors for our dark mode. We can reuse the same code from light scheme and change it to dark. Then change the text color to white and background to grey.
@media (prefers-color-scheme: dark) { .site-title a:link, .site-title a:visited, .header-social-icons .social-icons-menu li a { color: #fff; } .site-content, body { background: #141414; } .site-header { background: #141414; } }
Now if I change the my windows setting to dark theme my website will also switch the color.
Now couple things we need to be careful. First, I still keep the original CSS color setting. This is to provide fallback support for old browsers. prefers-color-scheme is now working on all majors browsers. Thanks to the latest version of Edge that is based on Chromium. Still, there is IE and some users who haven’t update their browsers.
Second, you’ll need to always place the dark mode code after the original. This because we’re using the same selector and the next one will override the previous one. unless you want to use !important or adding extra class for specificity.
And that’s all for this tutorial. Hope you guys enjoy. If you love this video. Don’t forget to subscribe our channel for more.