css中用z-index来控制定位元素的层叠顺序。
z-index
integer auto
整数值越大,元素离我们越近。
一旦给一个定位元素设定了z-index的值(不是auto),那么它就为它的所有后代建立了一个新的局部层叠上下文,如:
<html>
<head>
<title>Z-Index</title>
<style type = "text/css">
.one {
background: green;
position: absolute;
padding: 10px;
width: 500px;
height: 300px;
border: 2px solid black;
z-index: 7; /*z-index设置为7*/
top: 40px;
left: 60px;
}
.one-one {
background: orange;
position: absolute;
width: 200px;
height: 200px;
border: 2px solid black;
z-index: -10; /*z-index设置为-10*/
top: 50px;
left: 60px;
}
.one-two {
background: gray;
position: absolute;
width: 200px;
height: 200px;
border: 2px solid black;
z-index: -20; /*z-index设置为-20*/
top: 70px;
left: 30px;
}
.two {
background: red;
position: absolute;
width: 600px;
height: 300px;
border: 2px solid black;
z-index: 5; /*z-index设置为5*/
}
</style>
</head>
<div class = "one">one
<div class = "one-one">
one-one
</div>
<div class = "one-two">
one-two
</div>
</div>
<div class = "two">
two
</div>
<body>
</body>
</html>
运行结果:
从结果中可以看出,第一个div(绿色表示)位于第二个div(红色表示)上面,并且第一个div的第一个子元素(黄色表示)和第二个子元素(灰色表示)都位于第二个div的上面,尽管第二个div的z-index为正,而这两个子div的z-index为负。因为这两个子div的z-index是处于第一个div的z-index上下文中,相当于它们和第一个div共享了z-index = 7的值,而这个值比第二个div的z-index = 5大,所以他们位于上面。
更详细的介绍请参看《KB013: 分层的显示(Layered presentation)》。