结合两个不同父项的嵌套元素的 z-index 及其堆叠上下文

Combine z-indexes of nested elements of two different parents and their stacking context

我一直在网上搜索我的问题的解决方案。到目前为止我找到的所有文档都暗示我想要实现的目标是不可能的。那么,是这样吗?用文字描述问题:

现在,挑战部分是这 2 个简单的规则:

我们可以欺骗堆叠上下文来实现下面的视觉效果吗?

也欢迎使用 JS 解决方案,但要知道我使用的是 React,我不能直接进行 DOM 操作,父级和兄弟级关系是必须的。

这里有一个 JS fiddle playground 可以帮助您对此进行试验。 Fiddle 不是解决方案,它具有作为父实体兄弟姐妹的叠加层。

尝试将叠加层嵌套在父级中。

您可以从实体中删除 z-index 以防止它们创建堆叠上下文,并在叠加层上使用负数 z-index 将它们放在后面。

在下面的代码中,由于语义原因,我通过伪元素定义了叠加层,但是对于真正的子元素,它的工作方式完全相同。

#entities-wrapper {
  position: relative; /* Only the wrapper (and overlays) establish */
  z-index: 0;         /* stacking contexts, entities don't.        */
}
.entity, .entity::after {
  position: absolute;
}
.entity { /* Do not use z-index here */
  width: 100px;
  height: 100px;
  text-align: center;
  font-size: 16px;
  line-height: 100px;
}
.entity::after { /* This is the overlay */
  content: '';
  display: block;
  left: 50%;
  top: 50%;
  margin-left: -150px;
  margin-top: -150px;
  width: 300px;
  height: 300px;
  background: rgba(0,0,0,0.25);
  border-radius: 150px;
  z-index: -1; /* Behind the entities */
}
#a {
  background: red;
  top: 150px;
  left: 200px;
}
#b {
  background: yellow;
  top: 150px;
  left: 350px;
}
<div id="entities-wrapper">
  <div id="a" class="entity">parent entity A</div>
  <div id="b" class="entity">parent entity B</div>
</div>