CSS 父子層 z-index 問題 有趣範例
做前端切版這麼久,一直覺得自己對切版能應付9成以上的版型,但今天遇到一個基礎的問題,卻考倒了自己。
HTML
<div class="adiv"></div>
<div class="bdiv">
<div class="r-box">
<div class="cdiv"></div>
</div>
</div>
CSS
.adiv {
width: 300px;
height: 300px;
background-color: #000;
position: fixed;
z-index: 21;
}
.bdiv {
width: 300px;
height: 300px;
background-color: #ff00ff;
position: fixed;
left: 100px;
top: 100px;
z-index: 20;
}
.cdiv {
width: 300px;
height: 300px;
background-color: #00ff00;
position: absolute;
left: 100px;
top: 100px;
z-index: 22;
}
.r-box {
position: relative;
width: 100%;
height: 100%;
}

如果 HTML 不可更動
要怎麼將
bdiv放最底層
adiv放中間
cdiv放最上層
平常在寫這樣的版型其實沒甚麼難度,改一下HTML就能輕鬆搞定。
解決方案1
HTML
<div class="bdiv">
<div class="adiv"></div>
<div class="r-box">
<div class="cdiv"></div>
</div>
</div>
CSS
.adiv {
width: 300px;
height: 300px;
background-color: #000;
position: fixed;
z-index: 21;
left: 0;
top: 0;
}
.bdiv {
width: 300px;
height: 300px;
background-color: #ff00ff;
position: fixed;
left: 100px;
top: 100px;
z-index: 20;
}
.cdiv {
width: 300px;
height: 300px;
background-color: #00ff00;
position: absolute;
left: 100px;
top: 100px;
z-index: 22;
}
.r-box {
position: relative;
width: 100%;
height: 100%;
}

就能達成,但是因為HTML不可更動,讓人覺得不可能,
網路上的大神,總會有方法,請教IT幫,也讓我開眼界
解決方案 – 正確解法
HTML
<div class="adiv"></div>
<div class="bdiv">
<div class="r-box">
<div class="cdiv"></div>
</div>
</div>
css
.adiv {
width: 200px;
height: 200px;
background-color: #000;
position: absolute;
z-index: 2;
}
.bdiv {
width: 300px;
height: 300px;
background-color: #ff00ff;
}
.cdiv {
width: 300px;
height: 300px;
background-color: #00ff00;
position: relative;
left: 100px;
top: 100px;
z-index: 3;
}
.r-box {
position: relative;
width: 100%;
height: 100%;
}
將bdiv的position刪除,這樣cdiv的z-index就可以影響adiv,就能達成我需要的樣式。