使用定位布局时,可能会出现盒子重叠的情况。此时,可以使用z-index来控制
盒子的前后次序(z轴)
语法:
选择器{
z-index:1;
}
特点:
数值可以是正整数、负整数或0,默认是auti,数值越大,盒子越靠上
代码栗子:
.w {
/* 绝对定位:绝对不占有位置 */
position: absolute;
top: 0;
left: 0;
height: 200px;
width: 200px;
}
.xiongda {
background-color: red;
/*添加顺序,数越大,越靠上 */
z-index: 1;
}
.xionger {
background-color: aquamarine;
/* 熊二的z-index: 2;大于熊大的1,所以熊二在最上面 */
z-index: 2;
}
.gtq {
background-color: burlywood;
}
</style>
</head>
<body>
<div class="w xiongda">熊大</div>
<div class="w xionger">熊二</div>
<div class="w gtq">光头强</div>
</body>
分析:
position: absolute;绝对定位,盒子会浮起来,不占有自己原来的位置,便于演示。
当把定位的代码注释后。光头强在最上面。
把定位的代码取消注释后,熊二在最上面。数值越大越靠上