How to Create a Dark / Light Mode for Websites

ui-ux
Published on December 28, 2019

Use-Cases of this tutorial

  • Know how to give a dark or light theme to webpages depending on the mode chosen in the device settings.
  • Know about prefers-color-scheme CSS media query.

A website can be shown in dark / light mode using the prefers-color-scheme media query.

Giving user the preference of choosing a dark or light theme has become a very popular feature of operating systems.

Dark / light mode option setting in Android :

Dark / light mode option setting in Windows :

A dark color theme helps in reducing impact on the eyes. It can also increase the battery life of the device.

Using the prefers-color-scheme CSS media query, websites can be automatically displayed in dark or light theme as per the option chosen in the system's settings. prefers-color-scheme can detect whether the device is set to a dark or a light theme.

prefers-color-scheme can be queried against three values :

  • dark : This indicates that user can chosen a dark theme in their system.
  • light : This indicates that user can chosen a light theme in their system.

Depending on the current mode, specific CSS can be applied to elements.

.container {
    background-color: #336699;
    color: #333333;
}

/* CSS for dark mode */
@media (prefers-color-scheme: dark) {
    .container {
        background-color: #666666;
        color: white;
    }
}

/* CSS for light mode */
@media (prefers-color-scheme: light) {
    .container {
        background-color: white;
    }
}

Browser Compatibility

prefers-color-scheme is well supported by browsers. Currently Chrome, Firefox & Safari support it. Edge is moving to the Chromium engine from Jan 2020, so it should supported there as well.

In this Tutorial