层叠上下文(stacking context),是HTML中一个三维的概念。每个盒模型的位置是三维的,分别是平面画布上的X轴,Y轴以及表示层叠的Z轴。通常在元素发生堆叠时,就能看到某个元素可能覆盖了另一个元素或者被另一个元素覆盖。
层叠上下文可以理解成,在发生堆叠的时候,当前元素和其子元素变成了一个整体,按照当前元素的层级堆叠。
是指排列规则,如下:
border < z-index负值 < block < float < inline < z-index为0或者auto < z-index正值
即: 层叠上下文元素在子级元素下面, 自己元素根据不同属性来排列,相同属性则是后面的优于前面的。
例子:
<style>
.item{
width: 300px;
padding-top: 10px;
}
.father{
position: relative;
background: rgb(255,255,0);
}
.block{
background: rgb(255, 0, 0);
width: 100px;
height: 120px;
}
.float{
float: left;
background: rgb(0,255,255);
width: 100px;
height: 100px;
margin-left: 50px;
}
.inline{
margin-left: -100px;
background: rgb(0,255,0);
}
.zIndex-1{
position: absolute;
width: 300px;
height: 200px;
background: rgb(255,0,0);
left: 0;
top: 0px;
z-index: -1;
}
.zIndex0{
position: absolute;
width: 200px;
height: 100px;
background: rgb(0,255,0);
left: 0;
top: 100px;
z-index: 0;
}
.zIndexAuto{
position: absolute;
width: 150px;
height: 150px;
background: rgb(255,0,255);
left: 0;
top: 50px;
z-index: auto;
}
.zIndex1{
position: absolute;
width: 100px;
height: 50px;
background: rgb(0,255,255);
left: 0;
top: 150px;
z-index: 1;
}
</style>
<div class="item">
验证: inline > float > block > border
<div class="father">
<span class="inline">inline元素</span>
<div class="float">float元素float元素float</div>
<div class="block">块级元素</div>
</div>
</div>
<div class="item">
验证: 正 > 0 = auto > 负值 (但是 0 和 auto 会有所区别 0会新建层叠上下文)
<div class="father">
<div class="zIndex1">正z-index</div>
<div class="zIndexAuto">z-index:auto</div>
<div class="zIndex0">z-index:0</div>
<div class="zIndex-1">负的z-index</div>
</div>
</div>
原文:https://www.cnblogs.com/cyrus-br/p/14031169.html