【CSS】使用 z-index 属性值控制定位盒子的堆叠顺序 ( 多个盒子堆叠次序问题 | z-index 属性值简介 | 控制盒子堆叠次序 )
一、多个盒子堆叠次序问题
在 网页布局 中 , 如果 多个盒子都设置 绝对定位 , 那么这些盒子会堆叠在一起 ;
设置了定位样式的盒子会压住标准流盒子 , 如果有多个设置定位的盒子 , 后面的盒子会压住前面的盒子 ;
下面的代码中 , 三个盒子都设置了绝对定位 , 先设置了蓝色盒子 , 然后设置了 红色盒子 , 最后设置了 紫色盒子 ;
最终展现出来的样式是 紫色盒子 压住了 红色盒子 , 红色盒子压住了 蓝色盒子 ;
代码示例 :
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>堆叠次序</title><style>.one,.two,.three {/* 为 3 个元素 设置 绝对定位 */position: absolute;width: 200px;height: 200px;background-color: blue;}.two {/* 绝对定位 上边偏移 50 像素 */top: 50px;/* 绝对定位 左边偏移 50 像素 */left: 50px;background-color: red;}.three {/* 绝对定位 上边偏移 100 像素 */top: 100px;/* 绝对定位 左边偏移 100 像素 */left: 100px;background-color: purple;}</style>
</head>
<body><div class="one"></div><div class="two"></div><div class="three"></div>
</body>
</html>
显示效果 :
二、z-index 属性值简介
使用 z-index
属性 , 可以设置 堆叠层级 , 数值越大 , 越靠上 ;
z-index
属性取值范围 : 负整数 / 正整数 / 0 ;z-index
属性默认值为 0 ;z-index
属性值相同 , 那么按照先后顺序 , 后来的覆盖之前的 ;z-index
属性值的数字后面没有单位 ;
z-index 属性 生效的情况 :
- 相对定位
- 绝对定位
- 固定定位
在其它情况 , 如 : 静态定位 , 浮动 , 标准流 下 , z-index
属性无效 ;
三、控制盒子堆叠次序
这里设置 蓝色盒子 z-index: 3
, 红色盒子 z-index: 2
, 紫色盒子 z-index: 1
;
设置完毕后 , 蓝色盒子 压住 红色盒子 , 红色盒子 压住 紫色盒子 ;
代码示例 :
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>堆叠次序</title><style>.one,.two,.three {/* 为 3 个元素 设置 绝对定位 */position: absolute;width: 200px;height: 200px;background-color: blue;}.one{z-index: 3;}.two {/* 绝对定位 上边偏移 50 像素 */top: 50px;/* 绝对定位 左边偏移 50 像素 */left: 50px;background-color: red;z-index: 2;}.three {/* 绝对定位 上边偏移 100 像素 */top: 100px;/* 绝对定位 左边偏移 100 像素 */left: 100px;background-color: purple;z-index: 1;}</style>
</head>
<body><div class="one"></div><div class="two"></div><div class="three"></div>
</body>
</html>
执行结果 :