css

z-index について

z-indexは要素が重なった場合にどちらを優先的に表示するかを指定する事が出来るプロパティです。

前提

position プロパティを指定する要素の場合、有効になります。

基本

要素を上下左右中央寄せにする場合、position プロパティを使用する事があります。

HTML

<div class="sample"></div>

CSS

.sample {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #296971;
}

.sample::before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  content: 'index-A';
  height: 100px;
  width: 100px;
  margin: auto;
  background-color: #ffd700;
}

結果

確認

要素の重なり

要素を重ねてみます。

HTML

<div class="sample"></div>

CSS

.sample {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #296971;
}

.sample::before {
  position: absolute;
  top: 80px;
  right: 80px;
  content: 'index-A';
  height: 100px;
  width: 100px;
  margin: auto;
  background-color: #ffd700;
}

.sample::after {
  position: absolute;
  bottom: 80px;
  left: 80px;
  content: 'index-B';
  height: 100px;
  width: 100px;
  margin: auto;
  background-color: red;
}

結果

after要素(index-B)の方が優先的に表示される事が分かります。

要素の重なりの順序指定

z-indexを指定して、重なった要素の表示順位を入れ替えてみます。

HTML

<div class="sample"></div>

CSS

.sample {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #296971;
}

.sample::before {
  position: absolute;
  top: 80px;
  right: 80px;
  content: 'index-A';
  height: 100px;
  width: 100px;
  margin: auto;
  background-color: #ffd700;
  z-index: 3;
}

.sample::after {
  position: absolute;
  bottom: 80px;
  left: 80px;
  content: 'index-B';
  height: 100px;
  width: 100px;
  margin: auto;
  background-color: red;
  z-index: 2;
}

結果

before要素(index-A)の方が優先的に表示される事が分かります。

親要素との順位

position: absolute を指定した子要素の z-index を指定した場合、position: relative を指定した親要素が優先的に表示されます。

HTML

<div class="sample"></div>

CSS

.sample_04 {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #296971;
}
.sample::before {
  position: absolute;
  top: 80px;
  right: 80px;
  content: 'index-A';
  height: 100px;
  width: 100px;
  margin: auto;
  background-color: #ffd700;
  z-index: 1;
}

.sample::after {
  position: absolute;
  bottom: 80px;
  left: 90%;
  content: 'index-B';
  height: 100px;
  width: 100px;
  margin: auto;
  background-color: red;
  z-index: -1;
}

結果

after要素(index-B)のz-indexがマイナスなので親要素に隠れてしまう事が確認出来ます。

最後に

特にありません。

© DeNnie.Lab All Rights Reserved.