z-index

z-index は CSS のプロパティで、位置指定要素とその子孫要素、またはフレックスアイテムやグリッドアイテムの z 順を定義します。 z-index がより大きな要素はより小さな要素の上に重なります。

試してみましょう

位置指定されたボックス(つまり、positionstatic 以外のもの)では、z-index プロパティが以下のことを定義します。

  1. 現在の重ね合わせコンテキストにおけるボックスの重ね合わせレベル
  2. ボックスがローカルな重ね合わせコンテキストを作るかどうか

構文

css
/* キーワード値 */
z-index: auto;

/* <integer> 値 */
z-index: 0;
z-index: 3;
z-index: 289;
z-index: -1; /* 負の数はより低い優先度になる */

/* グローバル値 */
z-index: inherit;
z-index: initial;
z-index: revert;
z-index: revert-layer;
z-index: unset;

z-index プロパティは、キーワード auto または <integer> のどちらかで指定します。

auto

ボックスはローカルな重ね合わせコンテキストを新たに作りません。現在の重ね合わせコンテキストで作られたボックスは、親ボックスと同じ重ね合わせレベルを持ちます。

<integer>

この整数値は、現在の重ね合わせコンテキストで作られたボックスの重ね合わせレベルです。ボックスは重ね合わせレベル 0 のローカルの重ね合わせコンテキストを作ります。これは、子孫要素の z-index は、この要素の外部にある要素の z-index とは比較されないということです。

公式定義

初期値auto
適用対象位置指定要素
継承なし
計算値指定通り
アニメーションの種類integer
重ね合わせコンテキストの生成あり

形式定義

z-index = 
auto |
<integer> |
inherit

視覚的な階層を持つ要素

HTML

html
<div class="wrapper">
  <div class="dashed-box">破線のボックス</div>
  <div class="gold-box">金色のボックス</div>
  <div class="green-box">緑色のボックス</div>
</div>

CSS

css
.wrapper {
  position: relative;
}

.dashed-box {
  position: relative;
  z-index: 1;
  border: dashed;
  height: 8em;
  margin-bottom: 1em;
  margin-top: 2em;
}
.gold-box {
  position: absolute;
  z-index: 3; /* .gold-box を .green-box や .dashed-box の上に置く */
  background: gold;
  width: 80%;
  left: 60px;
  top: 3em;
}
.green-box {
  position: absolute;
  z-index: 2; /* .green-box を .dashed-box の上に置く */
  background: lightgreen;
  width: 20%;
  left: 65%;
  top: -25px;
  height: 7em;
  opacity: 0.9;
}

結果

仕様書

Specification
Cascading Style Sheets Level 2 Revision 2 (CSS 2.2) Specification
# z-index

ブラウザーの互換性

BCD tables only load in the browser

関連情報