Interactive Tutorial on Adding Dark Mode to Any Website
Published on 02 Jun 2021
| Updated on 03 Jun 2022
Written by Pranav Chakkarwar 10 min to read
Adding a dark mode is a great way to make any website visually appealing while making it more accessible. This article will guide you to add a toggle switch for dark theme. Read till the end to avoid missing any important details. If I miss something relevant, please contact me.
Toggle dark mode using a button
Click the lightning bolt to try it out.
Hello, here's some text to demonstrate changing of styles using a toggle.
Your preference will be saved in the browser's local storage as well.
To test it, try refreshing the page.
To modify the colors of the text, background, and svg fill, we’ll use CSS variables.
In the html, make sure the element with the id #toggle-button is inside the element with the id #themebuttondiv.
To detect the preferred theme on each page load, we’ll use the browser’s local storage API to save an user’s preference locally. This will come in handy if an user navigates to another page.
A simple if statement will get the job done.
The page will load initially with a light theme set by the init class. Whenver an user changes their theme, we need to check if the init class is present in the body tag. If it does, we’ll remove it and save the choice by storing a value in the local storage of the browser.
If an user decides to change the theme again, the if statement will render false but the else statement will restore the init class back to the body tag and delete the custom preference from the browser’s local storage.
Adjust to the user’s preference
We’ll use simple CSS Media Queries to identify an user’s preference from the browser’s settings.
Hello, here's some text to demonstrate the use of CSS media queries. To see the style update, change your theme configuration using Dev tools (Crtl + Shift + I). No reload requried :)
Combining both approaches
Taking it further
These approaches, however, may come with a number of drawbacks.