为什么 z-index 只适用于定位元素?

Bla*_*ick 7 html css

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

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

超文本标记语言

<div>
    <img class="not-positioned" src="http://placekitten.com/g/200/300">
    <img class="positioned" src ="http://placekitten.com/g/400/500">
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

<div>
    <img class="not-positioned" src="http://placekitten.com/g/200/300">
    <img class="positioned" src ="http://placekitten.com/g/400/500">
</div>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/666nzL6j/

您会注意到,这是根据规范工作的(尽管z-index 值较高,但.not-positioned图像位于图像后面),但我很难理解这种行为的基本原理。.positioned.not-positioned

mmg*_*oss 5

元素在所有三个维度上定位

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

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

因此,除了要设置元素position之外,您还需要为元素指定一个值。如果您的问题像示例中一样简单,您也可以给另一个元素一个否定:staticz-indexz-index

.positioned {
    position: relative;
    left: -60px;
    z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)