绝对定位的元素隐藏其前面的透明元素

2023-12-30

我有三个彼此相邻的块元素,第一个和最后一个是透明的,中间的是绝对定位的:

.box {
  width: 300px;
  height: 300px;
}
.box1 {
  background: yellow;
  opacity: 0.5;
}
.box2 {
  background: red;
  position: absolute;
  left: 0;
  top: 0;
  width: 800px;
  height: 800px;
}
.box3 {
  background: black;
  opacity: 0.5;
}
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>

Because .box1 and .box3被设置为opacity:0.5,我以为他们都会表现出来.box2, 但只有.box3做。为什么?


您可以使用z-index(最大的数字在顶部,最小的数字在下面)。

了解更多 :

  • 添加 z 索引 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Adding_z-index

该属性分配有一个整数值(正或负),表示元素沿 z 轴的位置。如果您不熟悉 z 轴,请想象页面有多层。每层都有编号。编号较大的图层会渲染在编号较小的图层之上。


.box {
  position:relative;
  width: 300px;
  height: 300px;
}
.box1 {
  z-index:20;
  background: yellow;
  opacity: 0.5;
}
.box2 {
  z-index:10;
  background: red;
  position: absolute;
  left: 0;
  top: 0;
  width: 800px;
  height: 800px;
}
.box3 {
  z-index:30;
  background: black;
  opacity: 0.5;
}
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

绝对定位的元素隐藏其前面的透明元素 的相关文章