关于z-index的困惑

Joh*_* L. 5 html css

以下链接中的文章指出z-index堆栈仅适用于兄弟元素:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

但是下面的代码片段显示,具有不同父级的div在z-index方面是堆叠的.即使文本和文本框都属于同一个父级而不是叠加层,叠加也会保留在文本框下方和文本框下方.根据这篇文章,这怎么可能?

.overlay {
    background-color: rgba(0, 0, 0, 0.5);
    display: block;
    height: 100%;
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 2;
}
Run Code Online (Sandbox Code Playgroud)
<div class="overlay" style="display: block;"></div>

<div>
    <div>
    Some text that will remain under the overlay.
    </div>
    <div style="width:1000px;">
        <div style="width:50%;position:relative;z-index:2;">
            <div>
                <input style="width:80%;">
            </div>

        </div>
    </div>

</div>
Run Code Online (Sandbox Code Playgroud)

小智 1

问题是您的 z-index 比较从第一个relativeabsolute定位的 DOM 元素开始。所以基本上 css z-index 会忽略所有具有static位置的元素。

 <div class="overlay" style="display: block;"></div>

<div style="position:relative;z-index:3;">
    <div>
    Some text that will remain under the overlay.
    </div>
    <div style="width:1000px;">
        <div style="width:50%;">
            <div>
                <input style="width:80%;">
            </div>

        </div>
    </div>

</div>
Run Code Online (Sandbox Code Playgroud)

我认为这应该对你有用