4

I am trying to invert the colors using css filter property. I have applied filter:invert(100%) in body. I want filter property should not affect <img /> element. I have added css :not(img) in body. But, it won't work.

.aaa {
  width: 100px;
  height: 100px;
  background: #00a3fe;
  margin: 5px
}
body:not(img) {
  filter: invert(90%)
}
<div class="aaa">

</div><div class="aaa">

</div>

<img src="http://pngimg.com/uploads/birds/birds_PNG115.png" />

1
  • 1
    body:not(img) { => body :not(img) { ... you need to put a space Commented Mar 21, 2019 at 6:27

1 Answer 1

2

You are missing space on the descendant selector so body:not(img) is equivalent to body and it's applying for the body tag itself.

.aaa {
  width: 100px;
  height: 100px;
  background: #00a3fe;
  margin: 5px
}
body :not(img) {
/*--^^^----*/
  filter: invert(90%)
}
<div class="aaa">

</div><div class="aaa">

</div>

<img src="http://pngimg.com/uploads/birds/birds_PNG115.png" />


UPDATE : Even in previous case it will cause issues when there are children elements so it's better to apply it for the body and apply the image as well so it will revert back.

.aaa {
  width: 100px;
  height: 100px;
  background: #00a3fe;
  margin: 5px
}

body {
  filter: invert(90%)
}

body img {
  filter: invert(90%)
}
<div class="aaa">

</div>
<div class="aaa">

</div>
<div>
  <img src="http://pngimg.com/uploads/birds/birds_PNG115.png" />
</div>

Or you have to apply filter specifically to element instead of wildcard selecting.

7
  • Here, In this simple case it is working. But, In large files/projects its not working body :not(img) Commented Mar 21, 2019 at 6:55
  • @KaruppiahRK may be the parent element gets the style applied Commented Mar 21, 2019 at 6:56
  • In that case, what is the solution? Commented Mar 21, 2019 at 6:58
  • @KaruppiahRK : apply twice to revert ..... check the update Commented Mar 21, 2019 at 7:01
  • that applies the filter twice actually... @KaruppiahRK apply the filter specifically to the elements that you need, if you apply it to a parent element it gets applied to the child elements too...
    – kukkuz
    Commented Mar 21, 2019 at 7:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.