Dark mode has gained a lot of attraction recently. Different Operating systems like Mac and Windows have adopted the dark and light mode for their UI. Similarly for mobile, different apps have been adopting the dark and light mode. For websites too, YouTube, Facebook and all other sites have these features. So as a frontend developer we should learn to develop this feature. Today I am going to design a Social Dashboard which will include a toggle switch for dark and light mode and we will have the mode change according to the system settings too. So, let’s get started.
You can find the source code for this project at https://gitlab.com/aneeslml/dark-mode So i wont be describing all the html and CSS aspects here, we will deal with just the mode changing functionality in this blog. For full reference please visit the source code.
At first let’s take the background color and text colors as variables. There are two colors for background, so let’s take primary-bg and secondary-bg for those. And two text colors so take them as primary-text and secondary-text. We will need color for hover too so let’s take it as hover variable.
We will take all the other social icon colors and basic colors as variables too which wont be needed to be changed according to mode.
Now, we will first write the html and css for light theme at the beginning with light color variables. And design the UI as following:
Here for toggle switch we’ll write code as:
Here, if the theme-toggler checkbox is checked then we will add an “active” class in our body tag, and if its unchecked then we will remove that “active” class. Therefore after adding an “active” class in body we will set new variables in css, that will change the color of background and text that we declared previously for light theme.
Thus after the addition of active class, the variables will change and the classes that were using those variables would adopt new variables that makes the webpage dark theme.
Operating System Settings
Now, to make our webpage change mode according to the system settings theme, we can use a media query named as “prefers-color-scheme” were we can assign the variables for that color-scheme as:
Hope you got the idea, you can check out the source code if any confusions or do comment below for any queries.