【问题标题】:Why element with z-index 0 is shown above element with z-index 1为什么 z-index 为 0 的元素显示在 z-index 为 1 的元素上方
【发布时间】:2017-05-31 17:24:01
【问题描述】:

我有以下代码(示例):

<div style="position: fixed">
  <div id="AAA" style="position: absolute; background-color: green; z-index: 1">AAA</div>
</div>
<div style="position: relative">
  <div id="BBB" style="position: absolute; background-color: red; z-index: 0">BBB</div>
</div>

对我来说,AAA div 应该显示在 BBB div 之上,因为:

  • 它们都指定了位置,并且该位置支持 z-index
  • AAA z-index (1) 高于 BBB z-index (0)

但在结果 HTML 中,BBB 显示在 AAA 之上。为什么?是否有任何文件描述了这种行为?

【问题讨论】:

  • 移除定位的外部 div 和内部 div 的行为方式

标签: css position z-index


【解决方案1】:

因为父级上的 positionz-index 会启动新的堆叠顺序。特别是position: fixed 在第一个元素上。 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

在以下场景中,任何元素在文档中的任何位置都可以形成堆叠上下文:

...

位置值为“固定”或“粘性”的元素(对所有移动浏览器都具有粘性,但对旧版桌面不适用)。

所以第一个 div 的子 z-index 是相对于父级的,而不是文档的其余部分。

在此示例中,您希望将 z-index 应用于父级。

<div style="position: fixed; z-index: 1;">
  <div id="AAA" style="position: absolute; background-color: green; z-index: 1">AAA</div>
</div>
<div style="position: relative;">
  <div id="BBB" style="position: absolute; background-color: red; z-index: 0">BBB</div>
</div>

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 2012-07-27
    • 2013-04-06
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多