【问题标题】:Position Fixed Child Restricted By Position Relative Parent Container's Z-index位置固定子项受位置相对父容器的 Z-index 限制
【发布时间】:2018-10-06 12:48:57
【问题描述】:

Position Fixed 元素总是相对于窗口定位自己。

但是,如果位置固定元素位于位置相对容器内,则位置固定子元素将遵循位置相对容器的 z-index。这意味着如果容器的任何兄弟姐妹也是相对的并且具有更高的 z-index,它们将覆盖位置固定的孩子。

示例:https://jsfiddle.net/r4n6Lzhx/2/

<style>

.container1 {
  position: relative;
  z-index: 2;
  height: 200px;
  width: 100%;
  background-color: yellow;
  box-shadow: 5px 5px 3px #888888;
}

.container2 {
  position: relative;
  background-color: green;
  z-index: 1;
  height: 200px;
}

.overlay {
  position: fixed;
  top: 50px;
  left: 50px;
  right: 50px;
  bottom: 50px;
  background: black;
  opacity: .8;
  z-index: 3;
}

</style>

<div class="container1"></div>
<div class="container2">
   <div class="overlay"></div>
</div>

有没有办法通过只改变孩子的CSS而不是父母的CSS来让固定位置的孩子“逃脱”父母的z-index?

所需的最终结果是容器 1 覆盖容器 2,但覆盖层(即容器 2 的子项)覆盖容器 1,我无法更改容器 1 或容器 2 的 CSS

【问题讨论】:

  • 我在 HTML 中制作或看到的所有叠加层始终是叠加层要覆盖的元素的后续兄弟元素。所以通常情况下,覆盖层将是 .container1 现在所在的位置。

标签: css css-position


【解决方案1】:

设置 container1 absolute 和 container2 relative 会重叠他们

container1 的 z-index 需要大于 container2 的 z-index,overlay 和 container1 的 z-index 相同。那么如果你不设置 container2 的 z-index 它将是 0 并且对于 container1 可以是 1 并且覆盖 2。

我编辑了container1的宽度,看到后面的container2,你可以设置回100%。

.container1 {
  position: absolute;
  z-index: 1;
  height: 200px;
  width: 90%;
  background-color: yellow;
  box-shadow: 5px 5px 3px #888888;
}

.container2 {
  position: relative;
  background-color: green;
  height: 200px;
}

.overlay {
  position: fixed;
  top: 50px;
  left: 50px;
  right: 50px;
  bottom: 50px;
  background: black;
  opacity: .8;
  z-index: 2;
}
<div class="container1"></div>
<div class="container2">
 <div class="overlay"></div>
</div>

【讨论】:

  • 感谢您的努力,但似乎我的规定不够清楚。我试图通过仅更改叠加层的 CSS 而不是容器的 CSS 来解决此问题。
  • 这很可能根本不可能
  • 很抱歉,我的英语不是最好的 :(。正如您所提到的,除非您从 container2 样式中删除 z-index,否则这是不可能的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2014-10-20
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多