- z-index:可以设置元素的叠加顺序,但依赖定位属性。
- z-index大的元素会覆盖z-index小的元素
- z-index为auto的元素不参与层级比较
- z-index为负值,元素被普通流中的元素覆盖
number设置z-index大小,number越大z-index越大。z-index只作用于带有定位属性的元素。如果position属性为static的时候,就相当于没有定位属性。在普通中也有层级关系的。
<style>
*{
margin: 0;
padding: 0;
}
.div1{
width: 100px;
height: 100px;
background: red;
position: relative;
}
.div2{
width: 100px;
height: 100px;
background: blue;
position: relative;
top: -50px;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
如果在.div1中加入
z-index: 1;
<style>
.div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
}
.div2{
width: 100px;
height: 100px;
background: blue;
position: relative;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
蓝色区域块把红色覆盖了。
原因是absolute没有设置left和top。
设置了之后还是覆盖了:
<style>
.div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
top: 0;
}
.div2{
width: 100px;
height: 100px;
background: blue;
position: relative;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
无论是absolute还是relative,层级关系依然是顺序关系。把absolute改成fixed也是这样。
<style>
.div1{
width: 100px;
height: 100px;
background: red;
position: relative;
}
.div2{
width: 100px;
height: 100px;
background: blue;
position: relative;
z-index: 10;
}
.per{
width: 200px;
height: 200px;
background: green;
position: relative;
z-index: 11;
top: -50px;
}
.test{
width: 100px;
height: 100px;
background: #ccc;
position: relative;
z-index: 1;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="per">
<div class="test"></div>
</div>
</body>
灰色框层级小,但是它显示出来了。受制于父元素的影响的优势,父元素的层级大于相邻元素的层级,无论它的级别有多小,都可以大于相邻的小于父元素的层级。