Use CSS to automatically enable dark mode in your web app based on system settings
Vasanth V
Posted on October 11, 2019
Dark mode toggle button has become a norm in web development now. But we can automatically enable dark mode based on system settings using pure CSS. (No more toggle buttons)
It's as easy as adding a media query to your CSS. This is how I added automatic dark mode in my app Hoy (hoy.sh). I use variables in my app so it became much more easy to enable it.
My CSS before adding dark mode:
:root {
--background-color: #f7f6ee;
--secondary-color: #fbfefb;
--text-dark: #101010;
--text: #333333;
--text-light: #7b7b85;
--text-lighter: #ababab;
--blue: #3498db;
--green: #27ae60;
--yellow: #feca57;
--red: #c0392b;
--white: #ffffff;
}
/* Sample css for an element */
body {
background: var(--background-color);
color: var(--text);
}
Media queries allow us to add CSS based on the system's colour preference using prefers-color-scheme
. For detailed documentation refer https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme.
So in order to enable dark mode based on the system settings, all I had to do is to add the below code in my CSS.
@media (prefers-color-scheme: dark) {
:root {
--background-color: #1e1f23;
--secondary-color: #232428;
--text-dark: #efefef;
--text: #c4c5c9;
--text-light: #6c6d71;
--text-lighter: #8e8f93;
}
}
Check out the automatic dark mode in my app at https://hoy.sh
Posted on October 11, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 11, 2019