z-index属性的适用范围
z-index属性使用在下面两种html元素中才会生效
- position属性设置为除static的其他属性值的元素
- display设置为flex的子元素
设置position
的情况
不设置position
<style>
.green{
width: 50px;
height: 50px;
z-index: 2;
background: green;
}
.blue{
width: 100px;
height: 50px;
margin-top: -20px;
background: blue;
z-index: 0;
}
</style>
<body>
<div class="green"></div>
<div class="blue"></div>
</body>
设置position
<style>
.green{
width: 50px;
height: 50px;
z-index: 2;
background: green;
position: relative;
}
.blue{
width: 100px;
height: 50px;
margin-top: -20px;
background: blue;
z-index: 0;
position: relative;
}
</style>
<body>
<div class="green"></div>
<div class="blue"></div>
</body>
父元素设置了display: flex
父元素不设置display: flex
<style>
.flex{
width: 200px;
height: 200px;
background: gray;
}
.green-child{
width: 50px;
height: 50px;
z-index: 1;
background: green;
}
.blue-child{
width: 100px;
height: 50px;
margin-top: -20px;
background: blue;
z-index: 0;
position: relative;
}
</style>
<body>
<div class="flex">
<div class="green-child"></div>
<div class="blue-child"></div>
</div>
</body>
父元素设置display: flex
<style>
.flex{
width: 200px;
height: 200px;
background: gray;
display: flex;
flex-direction: column
}
.green-child{
width: 50px;
height: 50px;
z-index: 1;
background: green;
}
.blue-child{
width: 100px;
height: 50px;
margin-top: -20px;
background: blue;
z-index: 0;
position: relative;
}
</style>
<body>
<div class="flex">
<div class="green-child"></div>
<div class="blue-child"></div>
</div>
</body>