主题
层级控制 z-index
CSS 的 z-index
属性用于控制定位元素(position
非 static)的叠放顺序,数值越大,元素越靠前显示。
1. 使用条件
- 只有定位元素(
position
为relative
、absolute
、fixed
或sticky
)才能使用z-index
。 - 默认值为
auto
,元素按文档顺序叠放。
2. 取值
- 整数(正负皆可),数值越大,层级越高。
auto
表示默认层级。
css
z-index: 10;
3. 应用场景
- 弹窗遮罩
- 下拉菜单覆盖内容
- 浮动按钮置顶
示例代码
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>z-index 层级示例</title>
<style>
.box {
position: absolute;
width: 150px;
height: 150px;
color: white;
font-weight: bold;
line-height: 150px;
text-align: center;
border-radius: 8px;
}
.box1 {
background-color: #ef5350;
top: 30px;
left: 30px;
z-index: 1;
}
.box2 {
background-color: #42a5f5;
top: 80px;
left: 80px;
z-index: 3;
}
.box3 {
background-color: #66bb6a;
top: 130px;
left: 130px;
z-index: 2;
}
</style>
</head>
<body>
<div class="box box1">z-index: 1</div>
<div class="box box2">z-index: 3</div>
<div class="box box3">z-index: 2</div>
</body>
</html>