Using mix-blend-mode on nested components with a different z-index

ε祈祈猫儿з 提交于 2021-01-28 11:58:34

问题


I have a setup that uses nested, absolute-positioned divs, and I need mix-blend-mode to blend the elements of a div with all of elements that have a lower z-index than that div.

The catch is that each div must have its own independent z-index (this cannot be changed for accessibility reasons).

This is easier to explain with an example:

#layer-1 {
  width: 700px;
  height: 700px;
  position: absolute;
  background-color: maroon;
  z-index: 1;
}

#layer-2 {
  position: absolute;
  height: 100px;
  width: 200px;
  z-index: 2;
}

#layer-3 {
  position: absolute;
  z-index: 3;
  mix-blend-mode: darken;
}

#layer-3 img {
  width: 300px;
}
<div id="layer-1"></div>

<div id="layer-2">

  <div id="layer-3">
    <img src="https://i.picsum.photos/id/100/2500/1656.jpg" />
  </div>

</div>

I need the image that's inside of layer-3 to blend with layer-1. If you remove the z-index from layer-2 in the fiddle, you will see that the blending works properly; however, this is not an option for accessibility reasons, as stated above.

I have made a jsfiddle here: https://jsfiddle.net/gabranches/v6cuL2o4/44/

Is there some way around this, or is this just a limitation of mix-blend-mode?


回答1:


Simply apply the mix-blend-mode to the div #layer-2. This one is on the same stacking context with #layer-1. #layer-3 or img cannot blend directly with #layer-1

#layer-1 {
  width: 700px;
  height: 700px;
  position: absolute;
  background-color: maroon;
  z-index: 1;
}

#layer-2 {
  position: absolute;
  height: 100px;
  width: 200px;
  z-index: 2;
  mix-blend-mode: darken;
}

#layer-3 {
  position: absolute;
  z-index: 3;
}

#layer-3 img {
  width: 300px;
}
<div id="layer-1"></div>

<div id="layer-2">

  <div id="layer-3">
    <img src="https://i.picsum.photos/id/100/2500/1656.jpg" />
  </div>

</div>

From the specification:

Everything in CSS that creates a stacking context must be considered an ‘isolated’ group. HTML elements themselves should not create groups.

An element that has blending applied, must blend with all the underlying content of the stacking context that element belongs to.

Related question for more detail about stacking context: Why can't an element with a z-index value cover its child?



来源:https://stackoverflow.com/questions/60873772/using-mix-blend-mode-on-nested-components-with-a-different-z-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!