CSS3--关于z-index不生效问题

参考文献: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;
}

 引申知识点CSS 7阶层叠水平

当两个元素层叠水平相同的时候,这时候就要遵循下面两个准则:

  1. 后来居上原则
  2. 谁 z-index 大,谁在上的准则

猜你喜欢

转载自www.cnblogs.com/ceceliahappycoding/p/11373809.html