在使用定位布局时,可能会出现盒子重叠的情况。
加了定位的盒子,默认后来者居上, 后面的盒子会压住前面的盒子。
应用 z-index
层叠等级属性可以调整盒子的堆叠顺序
z-index
的特性如下:
- 属性值:正整数、负整数或 0,默认值是 0,数值越大,盒子越靠上;
- 如果属性值相同,则按照书写顺序,后来居上;
- 数字后面不能加单位。
注意:z-index
只能应用于相对定位、绝对定位和固定定位的元素,其他标准流、浮动和静态定位无效。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.sanmao {
/*绝对定位*/
position: absolute;
width: 200px;
height: 200px;
margin: 150px;
background-color: red;
}
.damao {
position: absolute;
width: 200px;
height: 200px;
background-color: green;
}
.ermao {
position: absolute;
width: 200px;
height: 200px;
z-index: 2;
margin:100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="damao"></div>
<div class="ermao"></div>
<div class="sanmao"></div>
</body>
</html>