兄弟元素
看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 100px;
height: 100px;
background-color: #bfa;
position: absolute;
}
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 50px;
left: 50px;
}
.box3{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
top: 100px;
left: 100px;
}
</style>
</head>
<body>
<div class="box1">1</div>
<div class="box2">2</div>
<div class="box3">3</div>
</body>
</html>
可以看到,box3的层级最高。
如果想设置层级,则需要用z-index来设置层级,值越大,层级越高。
给box1设置1。
.box1{
width: 100px;
height: 100px;
background-color: #bfa;
position: absolute;
z-index:1;
}
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 40px;
left: 40px;
}
.box3{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
top: 60px;
left: 60px;
}
如果想把box2盖在box1前面,则可以给box2设置z-index:2。
如果设置的值相同,则在body中靠下的元素层级越高。
祖先元素
给box3添加一个子元素,并把box3的z-index设置最大。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 100px;
height: 100px;
background-color: #bfa;
position: absolute;
}
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 40px;
left: 40px;
}
.box3{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
top: 60px;
left: 60px;
z-index: 2;
}
.box4{
width: 50px;
height: 50px;
background-color: violet;
position: absolute;
z-index: 1;
}
</style>
</head>
<body>
<div class="box1">1</div>
<div class="box2">2</div>
<div class="box3">3
<div class="box4">4</div>
</div>
</body>
</html>
box3并没有盖住box4。
所以祖先元素不会盖住后代元素。