2015-02-11 92 views
4

我知道z-index只适用于定位元素,但我想知道为什么会出现这种情况。这种行为有没有很好的理由,还是仅仅是这些半任意规格决定中的一个?为什么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图像是背后的.positioned尽管.not-positioned的z-index值更高),但我很难理解此行为的基本原理。

谢谢。

+2

简单的谷歌搜索http://philipwalton.com/articles/what-no-one-told-you-about-z-index/ – crazymatt 2015-02-11 22:20:41

回答

3

元素定位在所有3个维度

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

当然z-index与其他人不是100%相似,因为它只描述了一个stackin g而不是“真实”的位置,但这就是你可以在z轴上执行的所有操作,因为在该轴上没有固定的边界。

所以,如果你想设置其z-index,你需要给一个元素position而不是static。如果你的问题很简单,只要在你的榜样,你也可以给其他元件,负z-index

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

感谢这个解释,以及一个将z-index设置为-1的备用方法。 – 2015-02-11 22:53:26

相关问题