五、z-index
● z-index值表示谁压着谁。数值大的压盖住数值小的。
● 只有定位了的元素,才能有z-index值。也就是说,不管相对定位、绝对定位、固定定位,都可以使用z-index值。而浮动的东西不能用。
● z-index值没有单位,就是一个正整数。默认的z-index值是0。
● 如果大家都没有z-index值,或者z-index值一样,那么谁写在HTML后面,谁在上面能压住别人。定位了的元素,永远能够压住没有定位的元素。
● 从父现象:父亲怂了,儿子再牛逼也没用。
没有单位:
1 z-index: 988;
Z-index值大的压住小的。
*{
margin: 0;
padding: 0;
}
.box1{
width: 200px;
height: 200px;
background: yellowgreen;
position: absolute;
top: 100px;
left: 100px;
z-index: 444;
}
.box2{
width: 200px;
height: 200px;
background: skyblue;
position: absolute;
top: 180px;
left: 180px;
z-index: 333;
}
<div class="box1">绿</div>
<div class="box2">蓝</div>
如果大家都没有z-index值,或者z-index值一样,那么谁写在HTML后面,谁在上面能压住别人。
* {
margin: 0;
padding: 0;
}
.box1 {
width: 200px;
height: 200px;
background: yellowgreen;
}
.box2 {
width: 200px;
height: 200px;
background: skyblue;
position: relative;
top: 100px;
left: 30px;
z-index: 999;
}
.box3 {
width: 200px;
height: 200px;
background: pink;
/*为了z-index值生效,必须加上一个定位:*/
position: relative;
top: 0;
left: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 200px;
height: 200px;
background: yellowgreen;
position: absolute;
top: 100px;
left: 100px;
z-index: 444;
}
.box2 {
width: 200px;
height: 200px;
background: skyblue;
position: absolute;
top: 180px;
left: 180px;
z-index: 333;
}
</style>
</head>
<body>
<div class="box1">绿</div>
<div class="box2">蓝</div>
</body>
</html>