首页 > 解决方案 > Position Fixed Child 受位置相对父容器的 Z-index 限制

问题描述

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

但是,如果位置固定元素位于位置相对容器内,则位置固定子元素将遵循位置相对容器的 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

标签: csscss-position

解决方案


Setting container1 absolute and container2 relative will overlap them

z-index of container1 needs to be greater than the z-index of container2 and same for overlay and container1. Then if you doesn't set z-index of container2 it will be 0 and for container1 can be 1 and overlay 2.

I edited the width of container1 to see the container2 behind, you can set it back to 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>


推荐阅读