概念
堆叠上下文,是一块区域,这块区域由某个元素创建,它规定了该区域中的内容在Z轴上排列的先后顺序。
创建堆叠上下文的元素
1.html元素(根元素)
2.设置了z-index(非auto)数值的定位元素
排列顺序
从后到前:
1.创建堆叠上下文的元素的背景和边框
2.堆叠级别(z-index)为负值的堆叠上下文
3.常规流非定位的块盒
4.非定位的浮动盒子
5.常规流非定位行盒
6.任何z-index是auto的定位子元素,以及z-index为0的堆叠上下文
7.堆叠级别为正值的堆叠上下文
每个堆叠上下文,独立于其他堆叠上下文,它们之间不能相互穿插
举例
.wrapper{
width: 1000px;
height: 700px;
border: 1px solid black;
position: relative;
z-index: 0;
}
.first{
position: absolute;
width: 350px;
height: 350px;
background-color: black;
z-index: -1;
left: 0;
top: 0;
}
.second{
width: 250px;
height: 250px;
background-color: red;
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
.third{
width: 150px;
height: 150px;
background-color: blue;
}
.fourth{
width: 120px;
height: 120px;
background-color: #008c8c;
float: left;
margin-top: -50px;
}
span{
background-color: yellow;
font-size: 20px;
/* margin-top: -150px; */
}
.sixth{
width: 100px;
height: 100px;
background-color: violet;
z-index: 0;
position: absolute;
}
.seventh{
width: 80px;
height: 80px;
background-color: green;
z-index: 2;
}
<div class="wrapper">
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
<div class="fourth"></div>
<span>我是非定位行盒</span>
<div class="sixth"></div>
<div class="seventh"></div>
</div>