【问题标题】:CSS Adding opacity to the background color of a div and not to the contentCSS 为 div 的背景颜色而不是内容添加不透明度
【发布时间】:2017-03-31 13:35:16
【问题描述】:

我正在尝试创建一个具有简单背景颜色和一些文本的 div。我想降低这个 div 的背景颜色的不透明度,但是当我这样做时,div 上的文本的不透明度也发生了变化。有没有办法只改变背景颜色的不透明度?

.main{
 background-color: red; 
  width: 100%;
  height: 200px;
  opacity: 0.5;
}
<div class="main">
  <p>Opacity of this text shouldn't be changed.</p>
</div>

【问题讨论】:

  • background-color: rgba(rr, gg, bb, 0.5).
  • 这个问题已经被问过Here。在 SO 上发布问题之前,请先尝试自己修复它,或者至少在 Google 上搜索它。我不赞成这个问题。
  • 抱歉,我没看到。我会确保在下次提问之前进行适当的研究。 @MuhammadUsman

标签: html css


【解决方案1】:

您可以使用下面颜色的alpha 通道,这是RGBA 中的第四个参数

rgba(255,0,0,0.1) /* 10% 不透明红色 /
rgba(255,0,0,0.4) /
40% 不透明红色 /
rgba(255,0,0,0.7) /
70% 不透明红色 /
rgba(255,0,0, 1) /
全不透明红色 */

注意:Red 将有255 作为第一个参数,其他作为0,您可以将第四个参数从0-1 更改为opacity

.main{
 background-color: rgba(255,0,0,0.7); 
  width: 100%;
  height: 200px;
  /*opacity: 0.5;*/
}
<div class="main">
  <p>Opacity of this text shouldn't be changed.</p>
</div>

【讨论】:

  • @Harish 我更新了你的代码,你可以执行看看效果。
  • @Harish Red255 作为第一个参数,其他参数作为0,您可以从0-1 更改第四个参数
【解决方案2】:

使用的 RGBA 颜色值是具有 Alpha 通道的 RGB 颜色值的扩展 - 指定颜色的不透明度。

RGBA 代表(红、绿、蓝、alpha)

.main{
 background-color: rgba(255, 0, 0, 0.5); 
  width: 100%;
  height: 200px;
}
<div class="main">
  <p>Opacity of this text shouldn't be changed.</p>
</div>

【讨论】:

  • 很高兴为您提供帮助:)
【解决方案3】:

.main{
 background:rgba(220,0,0,0.2);
  width: 100%;
  height: 200px;
}
<div class="main">
  <p>Opacity of this text shouldn't be changed.</p>
</div>

你可以像这样使用 CSS。

.main{
 background:rgba(170,0,0,0.2);
  width: 100%;
  height: 200px;
}

【讨论】:

    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2014-09-21
    • 2013-08-23
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多