Add Dark Mode to your Website

Tram Ho

Introduction

Dark Mode , also known as dark background mode, basically this mode will convert the light background (default) to the background with the dominant color is dark / black. This makes the display interface unchanged, but the color part changes drastically, besides, it also brings a lot of benefits including: benefits for human health (improving sleep, eyes, heart, facial skin ..), benefits with the device itself (improving performance, power consumption …)

In this article we will learn how to include darkmode for our website using CSS Variables .

Implement

We will add 3 options for users to choose including: Dark , Light and Auto . In addition to the already popular Light and Dark modes, here we have the Auto mode, the meaning of this mode is that it will be based on the theme settings of the system used to determine whether the current mode will be Light or Dark .

Adding the HTML

We will add the html snippet so that the user can choose between modes:

Adding the CSS

We will add a bit more CSS to the body tag, where we specify the color for the Light mode

To use CSS variables in the entire style sheet or where needed, we can add the following:

Next we will implement Dark mode by replacing the corresponding values ​​into the CSS variables just added above:

By this step basically 2 modes Dark and Light have worked. Now we will implement Auto mode:

Here we use Media Query to detect whether the current system’s settings are suitable for Dark mode. If the condition is met, the css snippet inside @media will be executed, details on prefers-color-scheme , you can refer to here .

We can test this Auto mode by adjusting the theme of the OS to darkmode or view the website through the phone with darkmode mode enabled.

Adding the JavaScript

The implementation of CSS for the 3 modes has been completed, in the next step we will add a little javascript to the dropdown list to choose between operating modes.

Here we handle the capture of the #theme change event to insert the corresponding class into the body tag

A step further – remembering the theme

In order to function more effectively, we will handle the browser will remember the mode previously set for refreshes, page transitions. To do this, we can use Local Storage .

First we need to save the selected theme value:

From subsequent calls, we will check this theme value to select the appropriate mode:

We will loop through each of the #theme options to check if the value savedTheme the savedTheme above or not, if so, we will set that value to be selected :

Refactor the DOMContentLoaded logic, so we get the following:

And the result: a

Summary

This article aims to introduce and learn about how to implement DarkMode for the website, the article is missing, thank you for taking the time to track.

Source and reference: https://dev.to/dcodeyt/add-dark-mode-to-your-websites-with-css-5bh4

Share the news now

Source : Viblo