为什么z-index仅适用于定位的元素? [英] Why does z-index only work for positioned elements?
问题描述
我知道z-index仅适用于定位的元素,但是我想知道为什么会这样.是否有任何适当的理由会导致这种行为,或者仅仅是那些半任意的规范决策之一?
I know that z-index only works with positioned elements, but I am wondering why this is the case. Is there any good reason for this behaviour or is it just one of those semi-arbitrary spec decisions?
在使用如下代码时,我遇到了这个问题:
I came across this issue when working with code like this:
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;
}
您会注意到,这符合规范(尽管 .not-positioned
.not-positioned 图像位于 .positioned
图像后面,code>的z-index值较高),但是我很难理解这种行为的原理.
You'll notice that this works according to specification (the .not-positioned
image is behind the .positioned
image despite .not-positioned
's higher z-index value), but I am having a hard time understanding the rationale for this behaviour.
谢谢.
推荐答案
元素在所有3个维度上定位
Elements are positioned in all 3 dimensions
- 在
- x轴上使用
left
和right
使用 - 在
- z轴上使用
z-index
top
和 bottom
在y轴上- on the x-axis using
left
andright
- on the y-axis using
top
andbottom
- on the z-axis using
z-index
当然 z-index
与其他代码并非100%相似,因为它仅描述堆叠而不是真实"位置,但这就是您可以在z轴上做的所有事情,因为您在该轴上没有固定的边界.
Of course z-index
is not 100% similar to the others, as it only describes a stacking instead of a "real" position, but that's all you can do on the z-axis, since you don't have fixed boundaries on that axis.
因此,如果要设置元素的 z-index
,则需要给元素赋予一个 position
值,而不是 static
.如果您的问题像您的示例中一样简单,则还可以给另一个元素一个负的 z-index
So, you need to give an element a position
value other than static
if you want to set its z-index
. If your problem is as simple as in your example, you can also give the other element a negative z-index
.positioned {
position: relative;
left: -60px;
z-index: -1;
}
这篇关于为什么z-index仅适用于定位的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!