## 事象
以下のようなコード。期待値は真っ赤の正方形が表示されること。
```html
<div>
<div style="z-index: 100; width: 32px; height: 32px; background-color: red"></div>
<div
style="
width: 24px;
height: 24px;
background-color: rgb(0, 0, 255, 0.5);
position: absolute;
top: 0;
left: 0;
"
></div>
</div>
```
しかし実際は期待通りにならない。
<div>
<div style="z-index: 100; width: 32px; height: 32px; background-color: red"></div>
<div
style="
width: 24px;
height: 24px;
background-color: rgb(0, 0, 255, 0.5);
position: absolute;
top: 0;
left: 0;
"
></div>
</div>
## 原因
[[positionが初期値(static)だとz-indexは効かない (CSS)|positionが初期値(static)だとz-indexは効かない]]から。
## 解決方法
[[position]]に`relative`などを指定する。
```html
<div>
<div style="position: relative; z-index: 100; width: 32px; height: 32px; background-color: red"></div>
<div
style="
width: 24px;
height: 24px;
background-color: rgb(0, 0, 255, 0.5);
position: absolute;
top: 0;
left: 0;
"
></div>
</div>
```
↓
<div>
<div style="position: relative; z-index: 100; width: 32px; height: 32px; background-color: red"></div>
<div
style="
width: 24px;
height: 24px;
background-color: rgb(0, 0, 255, 0.5);
position: absolute;
top: 0;
left: 0;
"
></div>
</div>
今回のケースだと、既に[[position]]が指定されている方の[[z-index]]をマイナスにして相対的に赤い四角系の優先度を上げる方法もある。
```html
<div>
<div style="width: 32px; height: 32px; background-color: red"></div>
<div
style="
z-index: -1;
width: 24px;
height: 24px;
background-color: rgb(0, 0, 255, 0.5);
position: absolute;
top: 0;
left: 0;
"
></div>
</div>
```
↓
<div>
<div style="width: 32px; height: 32px; background-color: red"></div>
<div
style="
z-index: -1;
width: 24px;
height: 24px;
background-color: rgb(0, 0, 255, 0.5);
position: absolute;
top: 0;
left: 0;
"
></div>
</div>