【问题标题】:Why does z-index only work for positioned elements? [duplicate]为什么 z-index 只适用于定位元素? [复制]
【发布时间】:2015-02-11 21:59:12
【问题描述】:

我知道 z-index 仅适用于定位元素,但我想知道为什么会这样。这种行为有充分的理由,还是只是那些半任意的规范决定之一?

我在使用这样的代码时遇到了这个问题:

HTML

<div>
    <img class="not-positioned" src="http://placekitten.com/g/200/300">
    <img class="positioned" src ="http://placekitten.com/g/400/500">
</div>

CSS

img {
    border: 2px solid black;
}

.positioned {
    position: relative;
    left: -60px;
    z-index: 1;
}

.not-positioned {
    z-index: 99;
}

http://jsfiddle.net/666nzL6j/

您会注意到这符合规范(尽管.not-positioned 的 z-index 值较高,但 .not-positioned 图像在 .positioned 图像后面),但我很难理解这种行为。

【问题讨论】:

标签: html css


【解决方案1】:

元素位于所有三个维度中

  • 在 x 轴上使用 leftright
  • 在 y 轴上使用 topbottom
  • 在 z 轴上使用z-index

当然,z-index 与其他的不是 100% 相似,因为它只描述了堆叠而不是“真实”位置,但这就是你在 z 轴上所能做的一切,因为你没有该轴上的固定边界。

因此,如果要设置元素的z-index,则需要为元素指定position 值而不是static。如果你的问题和你的例子一样简单,你也可以给另一个元素一个否定的z-index

.positioned {
    position: relative;
    left: -60px;
    z-index: -1;
}

【讨论】:

  • 感谢您的解释以及将 z-index 设置为 -1 的替代方法。
【解决方案2】:

来自 Mozilla 开发者网络 - position

position CSS 属性选择替代的定位规则 元素,旨在用于脚本动画效果。

因此,为了改变元素的位置,你需要告诉它不是静态的,你可以通过应用一个位置属性来做到这一点。

进一步阅读:

https://developer.mozilla.org/en-US/docs/tag/Understanding_CSS_z-index

【讨论】:

  • 最后一个链接坏了:"Page not found"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 2015-12-25
相关资源
最近更新 更多