Search code examples
htmlcssdarkmode

css "!important" not important enough: images colors stay inverted


I wanted to make a dark theme for a website and used something similar to the code below to invert the colors of everything in <body> except for the images.

I can't find out why this code doesn't work as I expected: as you can see, even with the !important, the image stays inverted:

body { background-color: grey; }

p { color: white; }

.body {
    -webkit-filter: invert(100%);
    -moz-filter: invert(100%);
    -o-filter: invert(100%);
    -ms-filter: invert(100%);
}
            
img {
    -webkit-filter: invert(0%) !important;
    -moz-filter: invert(0%) !important;
    -o-filter: invert(0%) !important;
    -ms-filter: invert(0%) !important;
}
<!DOCTYPE html>
<html>
    <head>
    </head>
    
    <body>
        <div class="body">
            <img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png" />
        </div>
        <p>The image above should be white</p>
    </body>
</html>

I wonder how important !important actually is, and what should I do to make the images not be inverted.

Of course I don't want to add a class/id to every image in the website, because even if I assume that that could solve my problem, it wouldn't be that efficient and easy to read.


Solution

  • Well, it's simple, you have to invert once more!

    We have learnt -1 * -1 = +1, just like that : Inversion*Inversion=Normal!
    so set the 0% of image to 100%,

    Tip: !important is not needed to override a rule, that is defined above it, this below rule will automatically override the above one, so you can even remove it.

    Answer code:

    body { background-color: grey; }
    
    p { color: white; }
    
    .body {
        -webkit-filter: invert(100%);
        -moz-filter: invert(100%);
        -o-filter: invert(100%);
        -ms-filter: invert(100%);
        filter: invert(100%);
    }
                
    img {
        -webkit-filter: invert(100%) !important;
        -moz-filter: invert(100%) !important;
        -o-filter: invert(100%) !important;
        -ms-filter: invert(100%) !important;
    }
    <!DOCTYPE html>
    <html>
        <head>
        </head>
        
        <body>
            <div class="body">
                <img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png" />
            </div>
            <p>The image above should be white</p>
        </body>
    </html>