13

i have a problem with the position: sticky and z-index

I want my modal in the sticky-element to be overlayed by the overlay. With position: relative it works: the modal is before the overlay. But when I use Sticky the modal is behind the overlay.

Hope it's understandable what I mean. Here's the example:

.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>

4

1 回答 1

12

设置position: relative时,.modal元素相对于主体,因为它具有position: fixed. 因此,z-index 值 1000 将其置于前台。

使用 时position: sticky,将使用.sticky默认的 z-index 值定位元素。因此,它将自己定位在后台,因为.overlay的 z-index 值为 999。.modal作为 的孩子.sticky,它永远无法走到 的前面.overlay

您必须更改 HTML 的结构,或者只是在.sticky元素上添加 z-index。

于 2018-11-01T18:46:27.937 回答