CSS 布局 - z-index 属性
z-index
属性用于指定元素的堆叠顺序。
z-index 属性
当元素进行定位时,它们可以与其他元素重叠。
z-index
属性指定元素的堆叠顺序(哪个元素应该在其他元素的前面或后面)。
元素可以具有正数或负数的堆叠顺序
这是一个标题

由于图像的 z-index 为 -1,它将显示在文本的后面。
注意: z-index
仅对 已定位元素(position: absolute, position: relative, position: fixed, or position: sticky)以及 flex 项(作为 display: flex 元素的直接子元素)有效。
另一个 z-index 示例
示例
在这里,我们看到具有较高堆叠顺序的元素总是显示在堆叠顺序较低的元素之上
<html>
<head>
<style>
.container {
position: relative;
}
.black-box {
position: relative;
z-index: 1;
border: 2px solid black;
height: 100px;
margin: 30px;
}
.gray-box {
position: absolute;
z-index: 3;
background: lightgray;
height: 60px;
width: 70%;
left: 50px;
top: 50px;
}
.green-box {
position: absolute;
z-index: 2;
background: lightgreen;
width: 35%;
left: 270px;
top: -15px;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="black-box">Black box</div>
<div class="gray-box">Gray box</div>
<div class="green-box">Green box</div>
</div>
</body>
</html>
自己动手试一试 »
不使用 z-index
如果两个已定位的元素相互重叠,而没有指定 z-index
,则 **在 HTML 代码中最后定义的元素** 将显示在上面。
示例
与上面相同的示例,但这里没有指定 z-index
<html>
<head>
<style>
.container {
position: relative;
}
.black-box {
position: relative;
border: 2px solid black;
height: 100px;
margin: 30px;
}
.gray-box {
position: absolute;
background: lightgray;
height: 60px;
width: 70%;
left: 50px;
top: 50px;
}
.green-box {
position: absolute;
background: lightgreen;
width: 35%;
left: 270px;
top: -15px;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="black-box">Black box</div>
<div class="gray-box">Gray box</div>
<div class="green-box">Green box</div>
</div>
</body>
</html>
自己动手试一试 »
CSS 属性
属性 | 描述 |
---|---|
z-index | 设置元素的堆叠顺序 |