How to Create a Dark / Light Mode for Websites

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.

no-preference : This indicates that user can made no preference regarding dark or a light theme.

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