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: fixed または position: 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">黒色のボックス</div>
  <div class="gray-box">灰色のボックス</div>
  <div class="green-box">緑色のボックス</div>
</div>
</body>
</html>

自分で試してみる

z-indexが指定されていない場合

二つの定位要素が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">黒色のボックス</div>
  <div class="gray-box">灰色のボックス</div>
  <div class="green-box">緑色のボックス</div>
</div>
</body>
</html>

自分で試してみる

CSS 属性

属性 説明
z-index 要素のスタッキング順序を設定します。