DEV Community

Vasanth V
Vasanth V

Posted on

Use CSS to automatically enable dark mode in your web app based on system settings

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);
}
Enter fullscreen mode Exit fullscreen mode

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;
  }
}

Enter fullscreen mode Exit fullscreen mode

Check out the automatic dark mode in my app at https://hoy.sh

Top comments (5)

Collapse
 
bayuangora profile image
Bayu Angora

Looks like normal as usual on my mobile browser. What kind of browser that support this CSS mode?

Collapse
 
vasanthv profile image
Vasanth V

Here is the browser support caniuse.com/#feat=prefers-color-sc...

Collapse
 
dorshinar profile image
Dor Shinar

It's usually an OS setting you should turn on (e.g. chrome on Windows will activate prefers-color-scheme: dark if you have dark theme turned on in your Windows settings)

Collapse
 
theankitjais profile image
Ankit Jaiswal

It works BUT how to add toggling button?
*if it is in dark mode, toggle in light & vice versa?

Collapse
 
mostafakheibary profile image
Mostafa Kheibary

you can just make class and after that with js add some toggle event listener on button
you can make it with css with toggle:checked and after that make the root color changes