Tol182 Tol182 - 2 months ago 6
CSS Question

Overwrite CSS filter invert not working in Mozilla Firefox

I'm writing small firefox add-on for comfortable reading pages at night. It should invert page colors but do not invert images.
The code is:

document.body.style.filter = "invert(100%)";

var imgs = document.getElementsByTagName("img");

for (var i = 0; i < imgs.length; i++) {
imgs[i].style.removeProperty("filter"); // NOT WORKING
imgs[i].style.filter = "invert(0%)"; // NOT WORKING EITHER
}


The problem is that it does not work as expected - the images still inverted, thouth inspect element inside firefox shows they have proper invert(0%) style.

Answer

If you invert the body that means all its contents are inverted. To display images in their original colors you need to invert them again, i.e. apply invert(100%) to them.

Note that this is different from CSS inheritance, filters conceptually apply when compositing the pixels of the box onto its parent, the images are inside the <body> box, that's why they get inverted too.

Small sidenote: You may want to apply it to the document.documentElement or :root selector – in most cases that's the <html> node – since bodies can be smaller than the viewport. Another thing to consider are frames nested inside inverted documents.

Comments