參考文獻:https://blog.csdn.net/u012207345/article/details/82744505
https://www.cnblogs.com/mrszhou/p/7745290.html
z-index 屬性是用來調整元素及子元素在 z 軸上的順序,當元素發生覆蓋的時候,哪個元素在上面,哪個元素在下面。通常來說,z-index 值較大的元素會覆蓋較低的元素。
z-index 的默認值為 auto,可以設置正整數,也可以設置為負整數。
只有定位的元素(即position
屬性值不是static
的元素)的z-index才會起作用。
z-index不生效的情況:
1.在用z-index的時候,該元素沒有定位(非static)
2.在有定位的情況下,該元素的z-index沒有生效,是因為該元素的子元素后來居上,蓋住了該元素,解決方式:將蓋住該元素的子元素的z-index設置為負數,而該元素不設z-index屬性.
<div class="dashed-box">Dashed box <span class="gold-box">Gold box</span> <span class="green-box">Green box</span> </div>
.dashed-box { position: relative; background: red; border: dashed; z-index: 1; height: 8em; margin-bottom: 1em; margin-top: 2em; } .gold-box { position: absolute; z-index: 3; /* put .gold-box above .green-box and .dashed-box */ background: gold; width: 80%; left: 60px; top: 3em; } .green-box { position: absolute; z-index: 2; /* put .green-box above .dashed-box */ background: lightgreen; width: 20%; left: 65%; top: -25px; height: 7em; opacity: 0.9;
}
.dashed-box { /* 去掉父元素中的z-index, 或者z-index:auto */ position: relative; background: red; border: dashed; height: 8em; margin-bottom: 1em; margin-top: 2em; } .gold-box { position: absolute; z-index: 3; /* 為了對比,保持不變 */ background: gold; width: 80%; left: 60px; top: 3em; } .green-box { position: absolute; z-index: -2; /* 改成負數 */ background: lightgreen; width: 20%; left: 65%; top: -25px; height: 7em; opacity: 0.9; }