Pankaj
Parashar developer

follow
email@pankajparashar.com

Dark Mode

Its not surprising that dark mode is the new fad in the town after Apple introduced the dark mode in MacOS. I decided to add a toggle button to switch to the dark mode on my blog.

May 29, 2020

I intentionally stayed away from using the CSS prefers-color-scheme media query to automatically apply the mode the user’s device is switched to. Instead we have a button in the header that will be used to toggle the dark mode. By default the site always loads in light/day mode.

Step 1

Identify all the colors in your stylesheet and qualify them under a naming scheme using CSS variables defined in the :root. Replace all the instances of each color value with its variable name , like var(--fore-color).

:root {
    --fore-color: #697076;
    --back-color: #fff;
    --primary-color: #21272a;
    --bq-color: #FCF7F4;
}

Step 2

Now you can define a new CSS class .dark that will override the values of these variables based on how you want your site to look like in the dark mode.

.dark {
    --fore-color: #ccc;
    --back-color: #21272a;
    --primary-color: #fff;
    --bq-color: #37474f;
}

Step 3

Its now time to add a toggle button that will toggle the class .dark everytime its clicked.

<a role="button" 
   onclick="document.body.classList.toggle('dark');return false"
   style="cursor:pointer">🌓</a>

Its done! Now you have a dark mode running on your site.

Did you enjoy reading this artice? I'd love to hear your thoughts. Feel free to send me a tweet or open an issue on Github to add your comments.

Next
What's new in Python 3.9

Previous
Look Ma! No Media Queries

2012-2020
Light/Dark

Back to Top