我的位置有问题:粘性和 z 索引
我希望粘性元素中的模态被覆盖层覆盖。 使用位置:相对它可以工作:模态位于覆盖之前。但是当我使用 Sticky 时,模式位于叠加层后面。
希望你能理解我的意思。 这是例子:
.sticky {
position: sticky; /* <-- dosen't work */
/* position: relative; /* <-- work */
top: 0;
width: 100%;
height: 200vh;
background: red;
}
.modal {
z-index: 1000;
position: fixed;
margin: 0 auto;
width: 200px;
height: 200px;
background: yellow;
margin: 0 auto;
}
.overlay {
z-index: 999;
position: fixed;
width: 100%;
height: 100%;
background: green;
top: 0;
bottom: 0;
left: 0;
right: 0;
opacity: 0.75;
}
<div class="overlay"></div>
<div class="sticky">
<div class="modal">modal</div>
</div>
当你设置
position: relative
时,.modal
元素是相对于body的,因为它有position: fixed
。因此,z-index 值 1000 将其置于前景中。
当您使用
position: sticky
时,.sticky
元素将使用默认的 z 索引值进行定位。因此,它会将自己定位在后台,因为 .overlay
的 z-index 值为 999。.modal
作为 .sticky
的子级,它永远无法位于 .overlay
前面。
您必须更改 HTML 的结构,或者只需在
.sticky
元素上添加 z 索引。
在我的例子中,我有粘性元素,它应该高于其他粘性元素
sticky1:
z-index: 10000
sticky2:
z-index: 1
absolute3:
z-index: 10001
以上永远不会起作用(absolute3不会出现在sticky1上方)
解决方案:
将 Sticky2 z-index 更改为 z-index 至少 10000