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.