把下面这个代码保存为test.html
<
meta
http-equiv
="Content-Type"
content
="text/html; charset=gb2312"
/>
< div id ="contain" style ="position: relative;" >
< div id ="box1" style ="position: absolute; top: 100px; left: 210px; width: 200px; height: 200px; background-color: yellow; z-index: 20;" > 这个box应该在上面 </ div >
</ div >
< div id ="box2" style ="position: absolute; top: 50px; left: 160px; width: 200px; height: 200px; background-color: green; z-index: 10;" > 这个box应该在下面,IE浏览器会对定位元素产生一个新的stacking context ,甚至当元素 z-index的为“auto”。 </ div >
< div id ="contain" style ="position: relative;" >
< div id ="box1" style ="position: absolute; top: 100px; left: 210px; width: 200px; height: 200px; background-color: yellow; z-index: 20;" > 这个box应该在上面 </ div >
</ div >
< div id ="box2" style ="position: absolute; top: 50px; left: 160px; width: 200px; height: 200px; background-color: green; z-index: 10;" > 这个box应该在下面,IE浏览器会对定位元素产生一个新的stacking context ,甚至当元素 z-index的为“auto”。 </ div >
分别在 firefox 和 IE 中打开,效果不一样吧。
到底是谁对呢?
其实是 firefox 是对的, 为什么这么说呢?我先说一下根据 Z-index 这个属性来显示元素的原理(根据CSS specification ):
1、元素的覆盖关系是根据 stacking context 来决定的,翻译过来就是:堆叠上下文环境,看起来很难理解吧,我把他叫做:堆叠元素,跟网页中的普通元素区分开来,一个html 的普通元素,比如一个<div>块,虽然是个<div>元素,只有它的 Z-index 被定义为一个非auto值时才产生堆叠元素,如果不定义 Z-index 的话默认为 auto 值,即不产生堆叠元素。
2、如果堆叠元素关系是平等的,则 Z-index 大的元素在 Z-index 小的元素之上,如果 Z-index 一样,则后来居上
3、Z-index 的大小关系是:正值 > 0 > 负值
解释这个例子:
根据以上规则,contain 元素没有定义 Z-index 所以不产生 堆叠元素,这样 box1 跟 box2 产生的堆叠元素是平等的,所以 box1(黄) 应该在 box2(绿) 之上,firefox 是对的
而IE有个BUG,它把 contain 也产生了一个堆叠元素并且设定Z-index 为0,于是 contain 跟 box2(绿)的堆叠元素是平等的,而contain 的 Z-index 为0,所以包含着 box1(黄)的contain就在 box2(绿)的下面了