一、概述
在日常code中,是否遇到过关于层级的问题,下面梳理下各种情况
二、首先来一张著名的7阶层叠水平图
换言之,除了z-index,display:inline-block,float,block也是可以控制元素层级显示的,ps:当元素有内容的时候,内容的层级会更高。
三、代码实现
首先是dom结构和样式代码,这里body当做是background来看
<body>
<div class="disblock">display:block</div>
<div class="zindex-1">z-index:-1</div>
<div class="float">float</div>
<div class="disin-block">display:inline-block</div>
<div class="zindex-0">z-index:0</div>
<div class="zindex1">正z-index</div>
</body>
<style>
body{
background: lightblue;
color: #fff;
font-size: 16px;
}
.disblock{
position: relative;
left: 100px;
top: 100px;
width: 500px;
height: 500px;
background: hotpink;
}
.zindex-1{
position: relative;
top: -500px;
left: 0;
width: 600px;
height: 600px;
background: purple;
z-index: -1;
}
.float{
position: relative;
top: -900px;
left: 200px;
float: left;
width: 400px;
height: 400px;
background: green;
}
.mydiv{
float: left;
width: 200px;
height: 200px;
background: #fff;
}
.mywrap{
width: 500px;
height: 500px;
background: #000;
}
.disin-block{
position: relative;
top: -800px;
left: -100px;
display: inline-block;
width: 300px;
height: 300px;
background: lightgreen;
}
.zindex-0{
position: relative;
width: 200px;
height: 200px;
top: -1000px;
left: 400px;
z-index: 0;
color: #000;
background: yellow;
}
.zindex1{
position: relative;
top: -1100px;
left: 500px;
width: 100px;
height: 100px;
z-index: 1;
background: red;
}
</style>
然后是效果图
四、注意事项
1、z-index的值的比较只能在同个层级上下文环境中,不同父元素的子节点的z-index的值是不能比较的;
2、开发中尽量避免层叠上下文的多层嵌套。避免使用太多的z-index值。