z-indexは要素が重なった場合にどちらを優先的に表示するかを指定する事が出来るプロパティです。
概要
z-index は、position プロパティを指定する要素に対して有効になります。
position プロパティを指定した要素に z-index を指定しない場合、z-index: 0 となります。
動作の確認
z-indexを指定しない場合
z-indeを指定しない場合、要素がどのように重なるかを確認します。
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を指定する場合
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)の方が優先的に表示される事が分かります。
z-indexにマイナスを指定する場合
z-indexにマイナスを指定する場合、当たり前ですが表示の優先度は低くなります。
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;
}
結果
親要素にz-indexを指定していないので、親要素は z-index: 0 となります。その為、after要素(index-B)のz-indexがマイナスなので親要素に隠れてしまう事が確認出来ます。
最後に
特にありません。