参考文献:https://www.cnblogs.com/mrszhou/p/7745290.html
对于一个已经定位的元素(即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;
}
