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放最上層
範例:https://codepen.io/ipphof/pen/vYKwOOB
你要的是這樣嗎?
https://codepen.io/ted59438/pen/eYzapjN
<div class="adiv"></div>
<div class="bdiv">
<div class="r-box">
<div class="cdiv"></div>
</div>
</div>
.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%;
}
沒辦法
規格裡有提到這段
Within a stacking context, child elements are stacked according to the same rules previously explained. Importantly, the z-index values of its child stacking contexts only have meaning in this parent. Stacking contexts are treated atomically as a single unit in the parent stacking context.
The main point about stacking contexts is that z-index can be used to rearrange the stacking order of elements only inside their own stacking context. That entire stacking context has a stacking position within its stacking context that’s determined by its z-index property and those of its siblings in that parent stacking context. Elements from different stacking contexts are therefore never interleaved in the final stacking order (this is what the spec means when it says stacking contexts are “atomic”).
簡單說
z-index 的作用範圍只到 parent container 為止
基本上子層很難覆蓋到父層以上的z-index。
也辦不到這件事。
在原理上,這樣的規劃也是對的。
所以你只能從你的節點來下手。
無法利用z-index
因為z-index只會作用於同層區分。