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 設置元素的堆疊順序。