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

来源:博客园 分类: 文章浏览史 发布时间:2020-09-30 14:53:56 最后更新:2020-09-30 浏览:851
转载声明:
本文为摘录自“博客园”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2020-09-30 14:53:56

参考文献: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;
}
复制代码

 

php技术微信