iT邦幫忙

0

請問CSS 父子層z-index 問題

  • 分享至 

  • xImage

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

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
6
通靈亡
iT邦高手 1 級 ‧ 2020-11-19 13:34:09
最佳解答

你要的是這樣嗎?
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%;
}

對喔!我都忘了還有 relative 這招。

咖咖拉 iT邦好手 1 級 ‧ 2020-11-19 13:47:29 檢舉

謝謝大大
這就是我要的樣式 /images/emoticon/emoticon41.gif

https://codepen.io/ipphof/pen/vYKwOOB

1
海綿寶寶
iT邦大神 1 級 ‧ 2020-11-19 12:28:52

沒辦法

規格裡有提到這段

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.

Mr.Z 的解釋更清楚

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 為止

1

基本上子層很難覆蓋到父層以上的z-index。
也辦不到這件事。

在原理上,這樣的規劃也是對的。
所以你只能從你的節點來下手。
無法利用z-index
因為z-index只會作用於同層區分。

我要發表回答

立即登入回答