首页 > 解决方案 > 如何在 CSS 中使内部 div 不透明度为 1?

问题描述

我正在尝试实现内部 div 不透明度 1,而其父 div 不透明度为 0.5。请找到我的codepen链接

https://codepen.io/SandeshSardar/pen/moVyEy

根据当前结果,即使在应用不透明度 1 后,内部 div 也会获得不透明度 0.5。

<div class="container">
<div  class="image">
  <div class="green" >
    <p>this div also should take opacity </p>
    </div>
    <div class="middle">

    </div>
</div>

    .container {
  position: relative;
  width: 50%;
}

.image {
position: absolute;
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
   background: red;
    height: 150px;
  width: 500px;
}

.middle {
  position: absolute;
  top: 50%;
  left: 50%;
  text-align: center;
  height: 50px;
  width: 50px;
  background-color: blue;
}

.container .image {
   background: rgba(255,0,0,.3);

}

.container .middle {
  opacity: 1;
  z-index: 9999;
}

.container .green {
 position: absolute;
  display: block;
  width: 100%;
   background: green;
    height: 50px;
  width: 500px;
}

标签: cssopacity

解决方案


您可以设置父 .image 与

background:rgba(255,0,0,0.5);

和孩子.middle

background:rgba(0,0,255,1);

rgba 的第四个值是不透明度!

编辑:

.container .green {
 position: absolute;
  display: block;
  width: 100%;
   background: rgba(0,255,0,1);
    height: 50px;
  width: 500px;
}

如果您希望 .green 的不透明度为 0.1,请将其更改为 rgba(0,255,0,0.1) 而不是 opacity: 0.1


推荐阅读