z-index的显示

背景

曾经的我天真地以为只要元素设置了定位,再设置z-index的话,z-index便决定了它在z轴的层叠顺序。

然而,前不久,有同事在解决bug时讨论了一下这个问题,发现事情并不简单。它还跟元素的父元素有没有z-index有关,也可以说是跟层叠上下文有关。

举个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.red {
height: 200px;
background-color: red;
}
.blue {
width: 100px;
height: 100px;
background: blue;
}
.yellow {
height: 200px;
background-color: yellow;
}
.green {
width: 100px;
height: 100px;
background-color: green;
}
</style>
</head>
<body>
<div class="red">
<div class="blue"></div>
</div>
<div class="yellow">
<div class="green"></div>
</div>
</body>
</html>

第一步,我们把绿色的移到蓝色的位置

1
2
3
4
5
6
7
.green {
width: 100px;
height: 100px;
background-color: green;
+ position: relative;
+ top: -200px;
}

好,绿色方块覆盖了蓝色方块,正常操作。

我们分别给蓝色和绿色设z-index

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.blue {
width: 100px;
height: 100px;
background: blue;
+ position: relative;
+ z-index: 3;
}
.green {
width: 100px;
height: 100px;
background-color: green;
position: relative;
top: -200px;
+ z-index: 2;
}

好,蓝色覆盖了绿色,现在还是正常操作。

现在我们分别给这两个div的父级div设置z-index。

1
2
3
4
5
6
7
8
9
10
11
12
.red {
height: 200px;
background-color: red;
+ position: relative;
+ z-index: 2;
}
.yellow {
height: 200px;
background-color: yellow;
+ position: relative;
+ z-index: 3;
}

这时你会发现,绿色重新覆盖了蓝色。而且即使我们把蓝色div的z-index设置的特别大,绿色依然覆盖了蓝色。

然后我去网上查资料后才发现,z-index值只决定同一父元素中的同级子元素的堆叠顺序。

因此,我们设置z-index时最好可以检查一下其父元素的z-index的影响。必要时,需要项目负责人,提前设置好各功能模块之间的z-index,这是最好不过了。

关于层叠上下文,有时间再说吧。