示例在这:
https://jsbin.com/qiquto/edit?html,css,output
示例中得效果是所期望的:.box
元素在最上层显示,伪元素被遮挡在后面。效果是通过为伪元素的z-index
设为负值实现的,但是当为.box
添加一个z-indx
属性时,它就会跑到最底层,而且把伪元素的z-index
·设为正值,.box
的z-index·
设为更大的值也无法达到相同效果,Why?
木有大师解释一下吗
1、:before
和:after
伪元素,box中的内容
都是 box的子元素
2、你设置 box
的z-index
是对box
本身和box
所在的环境下的同级有影响,但是对他的子集 内部的z-index
是没有影响的
3、而box
的内容和 :after
和:before
都是box
的同级子元素,所以:after
和:before
设置z-index
为负数 他们就会跑到同级的后面去了,所以 box
的内容层就会显示在他们之上
1,当使用position和z-index之后会创建新的stacking context结构
2,创建stacking context之后,内部的元素的从后向前的创建顺序如下:
Within each stacking context, the following layers are painted in back-to-front order:
1,the background and borders of the element forming the stacking context.
2,the child stacking contexts with negative stack levels (most negative first).
3,the in-flow, non-inline-level, non-positioned descendants.
4,the non-positioned floats.
5,the in-flow, inline-level, non-positioned descendants, including
inline tables and inline blocks.
6,the child stacking contexts with stack level 0 and the positioned
descendants with stack level 0.
7,the child stacking contexts with positive stack levels (least
positive first).``
3,当z-index不为auto时,创建新的stacking context,此时.box的border和background是属于1所描述的情况,所以始终是在最下面的
4,当z-index不存在,此时不创建新的stacking context,此时.box的3这种情况。故当设置z-index小于0时,即前面的2,就可以使.box覆盖在伪元素之上啦
参考:
z-index-when using pseudo
css stacking context