CSS 布局 - z-index 属性

z-index 属性指定元素的堆叠顺序。

z-index 属性

当元素被定位时,它们可能会与其他元素重叠。

z-index 属性指定元素的堆叠顺序(哪个元素应该放在前面,哪个元素应该放在后面)。

元素的堆叠顺序可以是正数或负数:

这是一个标题

因为图像的 z-index 为 -1,所以它将放置在文本后面。

实例

img {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}

亲自试一试

注意:z-index 仅适用于定位元素position: absoluteposition: relativeposition: fixedposition: sticky)和弹性项目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 设置元素的堆叠顺序。