Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding filter: grayscale to img elements hides overlaid elements

Tags:

html

css

Due to some fun little style guide changes, all images must be black and white. I figured a global style would take care of this:

img {
    filter: grayscale(100%)
}

It works like a charm, however: Elements that sit on top of images suddenly vanish. Ex: Text sitting on top of a banner image disappears, and a ::before element sitting on top of an image vanishes.

Is this expected behavior or is there something sinister going on?

EDIT:

The HTML is nothing special:

<div class="wrapper">
    <div class="header-text">
        <h2>My Header Text</h2>
    </div>
    <img src="myimage.png" />
</div>

.header-text is positioned absolutely.

like image 671
opticon Avatar asked Feb 22 '26 11:02

opticon


1 Answers

The filter affects the stacking order which can be adjusted by giving a z-index value to the header-text div.

This is documented in the spec.

Filter Property

A computed value of other than none results in the creation of a stacking context [CSS21] the same way that CSS opacity does.

.wrapper {
  position: relative;
}

.header-text {
  position: absolute;
  color: white;
  z-index: 1;
}

img {
  filter: grayscale(100%);
}
<div class="wrapper">
  <div class="header-text">
    <h2>My Header Text</h2>
  </div>
  <img src="http://www.placebacon.net/400/300?image=1" />
</div>
like image 134
Paulie_D Avatar answered Feb 25 '26 03:02

Paulie_D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!