以下链接中的文章指出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;
}
<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>
答案 0 :(得分:1)
问题是你的z-index比较是从第一个relative
或absolute
定位的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>
我认为这应该对你有用
答案 1 :(得分:-1)
文档内容如下:
每个堆叠上下文完全独立于其兄弟姐妹: 处理堆叠时只考虑后代元素。
这并不意味着堆叠上下文元素本身独立于其兄弟姐妹,但这意味着孩子们是。
请注意,堆叠上下文位于&#39;定位元素内。定位元素是具有位置&#39; relative&#39;,&#39; absolute&#39;或者&#39;固定&#39;和一个z指数。只有定位元素才能堆叠。在这种情况下,只有两个定位元素。他们自己堆叠上下文,就像他们最近的祖先一样。但是,这些项目似乎没有(共享)定位的祖先。基于此,我们可以说以下内容:
这些项目都属于相同的位置祖先(堆叠上下文):视口。因此,z索引给出了预期的结果(更高的z-index意味着在顶部)。等于z的索引出现在阅读顺序中(最后一个在顶部)。
正如列昂尼德所示,创建另一个定位的祖先会打破这种行为。这是因为这会创建一个新的独立堆叠上下文。
向第二个div添加不透明度也会破坏这种行为,因为需要重绘的元素(奇怪地)被处理为定位元素(新的堆叠上下文):
<div class="overlay" style="display: block;"></div>
<div style="opacity: 0.99;">...</div>
请参阅此操作:http://codepen.io/anon/pen/ENrOGx
仍然没有得到它?
阅读Philip Waltons的文章:https://philipwalton.com/articles/what-no-one-told-you-about-z-index/。他解释得非常好。
PS。谁不喜欢关于STACK溢出的好的堆叠问题?