位置固定元素始终相对于窗口定位自己。
但是,如果固定位置元素位于相对位置容器内,则固定位置子元素将服从相对位置容器的 z-index。这意味着如果容器的任何 sibling 也是相对的并且具有更高的 z-index,它们将覆盖位置固定的 child 。
示例: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。
最佳答案
设置container1 absolute和container2 relative会重叠
container1 的 z-index 需要大于 container2 的 z-index,overlay 和 container1 相同。然后,如果您没有设置 container2 的 z-index,它将为 0,对于 container1 可以为 1,overlay 为 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 - Position Fixed Child Restricted By Position Relative 父容器的 Z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50032496/