z-index 层叠顺序
一、z-index 概述
定位的元素脱离了正常文档流,他相当于漂浮在文档上面。那如果有很多个元素都用了定位,那如何确定这些元素的层叠顺序呢?
z-index 就是用来指定定位元素的堆叠顺序。
二、z-index 的特性
在同一层叠上下文中 z-index 值的特性:
- ✅
z-index的默认值是auto - ✅
z-index值可以是正数,也可以是负数 - ✅
z-index值越大,元素越在上面显示 - ✅
z-index值相同的元素,写在后面的会覆盖前面的 - ✅
z-index只针对定位元素有效,对其它元素无效
注意: 这里的"同一层叠上下文"是指元素都在同一个堆叠环境中,关于层叠上下文的详细概念会在后面讲解。
三、z-index 案例
案例1: z-index 值相同时
<style>
.box {
width: 200px;
height: 200px;
background-color: skyblue;
position: relative;
}
.item {
width: 100px;
height: 100px;
position: absolute;
}
/* item1与item2都未设置 z-index 值时,默认都为 auto */
/* 写在后面会覆盖在前面的上面 */
.item1 {
background-color: khaki;
left: 40px;
top: 40px;
}
.item2 {
background-color: rgb(255, 192, 203, 0.8);
top: 0;
left: 0;
}
</style>
<body>
<div class="box">
<div class="item item1">1</div>
<div class="item item2">2</div>
</div>
</body>结果: .item2 会显示在 .item1 的上面,因为写在后面。
案例2: z-index 值不同时
<style>
.box {
width: 200px;
height: 200px;
background-color: skyblue;
position: relative;
}
.item {
width: 100px;
height: 100px;
position: absolute;
}
.item1 {
background-color: khaki;
left: 40px;
top: 40px;
z-index: 3;
}
.item2 {
background-color: rgb(255, 192, 203, 0.8);
top: 0;
left: 0;
z-index: 1;
}
</style>
<body>
<div class="box">
<div class="item item1">1</div>
<div class="item item2">2</div>
</div>
</body>结果: .item1 显示在 .item2 的上面,因为 z-index: 3 > 1。
案例3: z-index 为负数
<style>
.box {
width: 200px;
height: 200px;
background-color: rgb(135, 208, 236, 0.5);
position: relative;
}
.item {
width: 100px;
height: 100px;
position: absolute;
}
.item1 {
background-color: khaki;
left: 150px;
top: 150px;
z-index: -1;
}
.item2 {
background-color: rgb(255, 192, 203, 0.8);
top: 160px;
left: 100px;
z-index: -2;
}
</style>
<body>
<div class="box">
box
<div class="item item1">1</div>
<div class="item item2">2</div>
</div>
</body>结果:
-1 > -2,所以.item1会显示在.item2的上面- 但因为
z-index是负值,所以会显示在.box盒子的下面
四、z-index 使用技巧
技巧1: 隐藏元素
.element {
z-index: -999; /* 显示在最底层,达到隐藏效果 */
}技巧2: 提升层级
.button {
position: relative;
z-index: 1; /* 确保文字在最上层显示 */
}技巧3: 遮罩层
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 100; /* 遮罩层 */
}
.modal-content {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 101; /* 内容层,高于遮罩层 */
}五、常见问题
问题1: z-index 不生效
原因: 元素没有定位
/* ❌ 不生效 */
.element {
z-index: 10;
}
/* ✅ 需要添加定位 */
.element {
position: relative;
z-index: 10;
}问题2: 子元素 z-index 无法超过父元素外部元素
原因: 父元素创建了层叠上下文,子元素的 z-index 只能在父元素的层叠上下文内比较
<style>
.parent1 {
position: relative;
z-index: 1; /* 创建层叠上下文 */
}
.child1 {
position: absolute;
z-index: 999; /* 在.parent1的上下文内 */
}
.parent2 {
position: relative;
z-index: 2; /* 高于.parent1 */
}
.child2 {
position: absolute;
z-index: 1; /* 在.parent2的上下文内 */
}
</style>
<body>
<div class="parent1">
<div class="child1">child1 z-index: 999</div>
</div>
<div class="parent2">
<div class="child2">child2 z-index: 1</div>
</div>
</body>结果: .child2 会显示在 .child1 上面,因为 .parent2 的 z-index: 2 > 1