Easy toggle between light or dark color schemes using CSS.
While developing a new theme for my personal blog in the midst of Coronavirus outbreak, I tried a much convenient method to change themes or have an option to change color schemes in a website. It is convenient in a way such that there is a minimal overhead to the data we need to track and it is amazingly fast and utilizes local variables in CSS.
This theme toggle method utilizes CSS Variable var(), a tiny metadata in our html in the front end, and storage for a simple string to keep track of our active theme.
Preparing the color schemes
There are two color schemes I prepared, light and dark. Keep the stylesheet as modular as possible. I like the combination of minimalistic and professsional color schemes therefore mixture of light colors and dark colors is my go-to. The colors and variable names are completely relative, it does not follow any specific standards, it is simply a variable and the color of my choice.
Using the theme in the front-matter.
Using the theme in our front matter is easy, all we need to do is add a new attribute called theme="light" or theme="dark" in <html> tag. My Jekyll blog’s <html> tag looks like this.
Mind you, there is no need to have theme="light" as we did not set-up any light theme variables to use therefore using the fallback to the root (by default).
Button to change the theme.
In order to toggle/change the theme between the light and dark, we need a button or an actionable component of sort. As someone who is bad at designing, I mean, bad.., I decided to simply use icons by Font Awesome as my button. Two lightbulb icons seemed simple and perfect enough for me.
Toggle functionality for the button.
I decided to use the regular type of lighbulb to denote the lightbulb’s off state whereas, the solid type of lightbulb denotes it’s on state. So, lightbulb’s on state means everything is light because the lightbulb is on, off state (regular type) means everything is dark because the lightbulb is off.
I suppose, I could have simplified it further but for now, we will leave it at basic.
That should be it, simple enough to change the theme without having to load different stylesheets and going through other hassles.