<div id="d2" style="background:blue; width:50px; height:50px; position:relative; top: -120px; z-index:9;">d2</div>
<div id="d3" style="background:green; width:50px; height:50px; position:relative; top: -80px; position:relative; z-index:11;">d3</div>
</div>

4. 前提:boxes属于不同的stacking context,并且stacking contexts为祖孙/父子关系
规则:属于子stacking context的box必定更靠近用户
CSS Code复制内容到剪贴板
<div style="background:blue; width:100px; height:100px; position:relative; z-index:10;">
<div style="background:red; width:50px; height:50px; position:relative; z-index:-10;"></div>
</div>

z-index的作用
啰嗦一句:同一个stacking context的z-index才具有可比性,也就是说在讨论z-index时必须带说明是哪个stacking context下的z-index。
它有两个作用:1. 设置box在其所属的stacking context下的stack level;
2. 当z-index属性值非0时,则在该box中创建一个新的stacking context,而该box的子孙box默认属于这个新stacking context。
注意:z-index的默认值为auto,自动赋值为0。因此默认情况下不会创建新的stacking context。
z-index生效的阀门
z-index属性值仅对positioned box生效,而non-positioned box的z-index永远为0。
也许你会举出如下反例:
JavaScript Code复制内容到剪贴板
<div id="d1" style="z-index:10;"></div>
<script type="text/javascript">
console.log(window.getComputedStyle(document.getElementById(‘d1’))[‘zIndex’]); // 输出10
</script>
但抱歉的是,上面获取的是non-positioned element div#d1的z-index属性值,而不是non-positioned box的z-index属性值。
对于positioned element,它会将z-index赋予给对应的positioned box,而non-positioned element则不会。










