Dark mode with css variables and vanilla js


Dark mode with css variables and vanilla js Tutorial by Mirko Zovko | 11. Oct. 2020.

In this article I’ll show you how to create dark mode for your website with help of css variables and a checkbox switcher function in vanilla js.

For this article html structure is not needed, you can add whatever elements you want, but for this feature to work you need to have one input with checkbox type which is going to be used as theme switcher between light and dark theme.

For tutorial purposes I created custom css switcher with icons and css animation:

Switcher is one of the three components that we need to make it all work. Next we need css variables for light and dark themes. And those variables we need to use in our css when we create other elements.

After we finished with that part, we needed a js function so that everything could work. In this function I added an additional feature and that is saving current theme in local-storage so when you reload the page it can get back to the theme that we chose. If we don’t add this part of the code then every time we reload the page it would return to the default theme, which is a light theme in our case.

Full code example you can check on jsFiddle or on Codepen.

I hope you liked this article. If you have some suggestions or ideas feel free to write in the comment section below. Enjoy! :)