easily implementing night mode using css

With night mode becoming more and more popular, you might want to add this feature to your next website/project. Thankfully, it is relatively easy to do. There are a couple of approaches to making an optional dark theme for your website:

change colors manually

The key is to set a class to the <body> tag when the night mode is on and write new CSS rules for every element you want to change the color of in night mode. This is the most conservative approach, easy on the resources and compatible with pretty much every browser out there. You can see how it can be implemented in this codepen:

See the Pen A basic night mode example by r3dm1ke (@r3dm1ke) on CodePen.0

use mix-blend-mode:difference

This one is way easier. I will not into details nor take the credit for it: I encourage you to check out this awesome post by Wei Gao – https://dev.wgao19.cc/2019-05-04__sun-moon-blending-mode/ . The only problem I encountered is I had problems with this not working in Chrome (while everything was fine in Firefox) and not being able to exclude some images from blending. One great advantage of this way is you can use some advanced animations.

use filter

This is the one used in the theme I wrote for this website. The principle is stupid simple: invert the whole page with a filter: invert(1) css property and invert everything you want to keep the same (images, embeds, etc.) once more. The support in browsers is very good, but you will still need a polyfill (something like https://github.com/Schepp/CSS-Filters-Polyfill) for IE. You can check this codepen out for code:

See the Pen A night mode example with filter:invert by r3dm1ke (@r3dm1ke) on CodePen.0

Thank you for reading and I hope this will be helpful for your next project.

Get new content delivered to your mailbox:

leave a comment