z-index 设置元素的层级
z-index后面跟正整数,数值越大,层级越高。
但是;
1 z-index属性必须要开启定位的前提下使用
2 设置z-index,父元素的层级再高也不会高于子元素
1.z-index的取值
1)关键字 :auto
2)数值: 任意整数(包括正数、负数、0)
3)通用取值:inherit initial unset
2.z-index 的作用
1)一般来说,z-index的默认值是auto
2)当z-index取数值时,有两个作用:
① 在当前元素建立一个堆叠上下文,即告诉浏览器这里出现了堆叠,需要考虑分层了。
② 告诉浏览器当前元素在这个堆叠上下文中所占的位置。
例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<style>
.box{
width: 100px;
height: 100px;
background-color: red;
}
.box1{
position: relative;
}
.box2{
background-color: green;
position: relative;
bottom: 50px;
left: 50px;
z-index:20;
}
.box3{
background-color: grey;
position: relative;
left: 100px;
bottom: 100px;
z-index: 21;
}
</style>
</head>
<body>
<div class="box1 box">1</div>
<div class="box2 box">2</div>
<div class="box3 box">3</div>
</body>
</html>
效果图如图所示:
box2的层级是20,box3的层级是21,所以box3在box2的上面,数值越高,层级越高。前提是在开启定位的情况下。
例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<style>
.box4{
width: 200px;
height: 200px;
background-color: pink;
position: relative;
z-index: 9999;
}
.box5{
width: 100px;
height: 100px;
background-color: blueviolet;
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box4">
<div class="box5">5</div>
</div>
</body>
</html>
效果图如图所示:
我们box5的层级是1,它的父元素box4层级是999,但是box4并没有在box5的上面,因为父元素的层级再高也不会高于子元素。