DEV Community

Cover image for [CSS Hack] Dark Mode Within a Second!
Al Nahian
Al Nahian

Posted on

[CSS Hack] Dark Mode Within a Second!

Thumbnail
Who doesn't like Dark Mode? In this CSS Hack, you'll learn about How To Convert a HTML Page to dark theme just using a single CSS property.
Let's see it in quick action!

In this post, we'll talk about a simple CSS filter property, which will invert colors and help us to get a Dark theme page instantly.
And the Magic Property Is:



html {
  filter: invert(100%) hue-rotate(180deg);
}


Enter fullscreen mode Exit fullscreen mode

I don't feel comfort reading documentation websites for a long duration, if it doesn't have any Dark Theme functionalities.
Light Theme
As we can see in the image above, the website is in pure white theme. So, reading text contents for so long at night, can give me real headache!

So how can I put all my attention together to complete reading those documentations? I can either install a Dark Mode enabler browser extension or go for a real quick solution like this.

If I open Inspect Element on my browser, and then select the <html> or the <body> tag using cursor, and add this little one liner css property to it's style tab just like this:
style tab
The entire webpage will magically turn into dark mode and the contents of the page will get some adorable colors just like below:
Webpage turned Dark

Finally, if you want to implement this real quick css magic trick in your website, then either you can append a toggler button or a checkbox or something. It's up to you!

Edit: One of my Facebook friends have asked me, "what if there are some images on the page? Will they get discolored? How you will fix that thing?"

Well!
In some cases, you may don't want image colors to be inverted. Then you can apply a global pseudo CSS rule like below to ignore all the images or the given argument tag inside the parameter



:not(img){
  filter: filter: invert(100%) hue-rotate(180deg);
}


Enter fullscreen mode Exit fullscreen mode

Check filter: invert() Browser Support
Browser Support

I know it's neither a secret trick, nor something new. But it's cool, right?

Invert filter is only good for monochrome or minimal color. If you have so many color, then you have to add more filter to those part to avoid unnecessary inverted.

Top comments (2)

Collapse
 
kabirtawhid profile image
kabirtawhid

Nice Trick Vai! I just tried it on your articles!

Collapse
 
alnahian2003 profile image
Al Nahian

Thanks for reading ☺
you can check my other articles on my profile too :)