DEV Community

Cover image for Poor Man's Dark Mode Using CSS Filter

Poor Man's Dark Mode Using CSS Filter

Rik Schennink on April 15, 2019

Tap the "dark mode" checkbox in the top right corner. The checkbox only toggles the dark-mode class on the <html> element. What does th...
Collapse
 
joeberetta profile image
Joe Beretta • Edited

Hi Rik!
You would to do it more shortener

:not(img) { filter: invert(100%) } 
Enter fullscreen mode Exit fullscreen mode

This selector will match everything(even html and body) except img tag)

Collapse
 
rikschennink profile image
Rik Schennink

Apart from selector performance, which often is negligible, I wonder if filtering every element OR only the top one would result in a noticeable rendering performance. Also, would this not result in multiple elements inverting their parent element filter?

Collapse
 
rdrahul profile image
Rahul Dwivedi

Add hue-rotate(180deg) as well, makes it much better

filter: invert(100%) hue-rotate(180deg);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
petee profile image
Petee

So clever!

Collapse
 
somedood profile image
Basti Ortiz • Edited

Ooh! Reminds me of the early prototypes of dev.to's dark mode. Good times...

Collapse
 
champi profile image
Champi • Edited
  • Crazy client:
    One more thing. I wunna dark mode toggle pls.

  • Me now:
    Here you go! (filter: invert(100%))

Just kiddin' [am I?]

Collapse
 
mooshmassacre profile image
Gustavo Dezen

Or don't lol

Collapse
 
bayuangora profile image
Bayu Angora

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.

One question about dark mode. Observatory (grade checker by Mozilla) will downgrade score to website that still use inline or <script>. </p> <p>How to fix this issue while dark mode toggle needs &quot;onclick&quot; to trigger and switch the light / dark mode?</p>

Collapse
 
scrabill profile image
Shannon Crabill

filter: invert(100%) is my new favorite thing.

Collapse
 
mooshmassacre profile image
Gustavo Dezen

It's a cool trick!

Collapse
 
yuanhao profile image
YuanHao Chiang

Some website's dark mode themes are so badly made that this would in fact look better 😅

Collapse
 
hyvyys profile image
Adam Jagosz

Sadly, as simple a thing as the invert filter could not be made consistent across browsers. Or is it just me?
CSS filter: invert different results in Chrome and Firefox

(FTR, Firefox does it correctly, but I designed the image to match Chrome first, and now poor Firefox seems like the bad guy).

Collapse
 
hyvyys profile image
Adam Jagosz

I reported the issue here bugs.chromium.org/p/chromium/issue...

Collapse
 
thomaslatt profile image
Thomas Latterner

Awesome!

Collapse
 
donaldng profile image
Donald Ng

Really cool hack, thanks for sharing!

Collapse
 
itscosmas profile image
Cosmas Gikunju

Haha this makes me a happy man 😂 😂 😂