CSS将不透明度添加到div的背景颜色而不是内容(CSS Adding opacity to the background color of a div and not to the content)

编程入门 行业动态 更新时间:2024-10-27 16:24:13
CSS将不透明度添加到div的背景颜色而不是内容(CSS Adding opacity to the background color of a div and not to the content)

我正在尝试使用简单的背景颜色和div上的一些文本创建一个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> 
  
 

I'm trying to create a div with a simple background color and some text on the div. I want to decrease the opacity of the background color of this div but when I do that the opacity of the text on the div is also getting changed. Is there a way to change the opacity of the background color only?

.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> 
  
 

最满意答案

您可以使用颜色的alpha通道,如下所示,这是RGBA的第4个参数

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的第4个参数更改为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> 
  
 

You can use the alpha channel of the color as below which is a 4th argument in RGBA

rgba(255,0,0,0.1) /* 10% opaque red / rgba(255,0,0,0.4) / 40% opaque red / rgba(255,0,0,0.7) / 70% opaque red / rgba(255,0,0, 1) / full opaque red */

Note: Red will have 255 as first argument and others as 0 and you can change the 4th parameter from 0-1 for 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> 
  
 

更多推荐

本文发布于:2023-07-26 18:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279573.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:透明度   将不   而不是   颜色   背景

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!