仅使用CSS,是否可以使元素的背景半透明,但元素的内容(文本和图像)不透明?

我想在不将文本和背景作为两个独立元素的情况下完成这一点。

尝试时:

p型{位置:绝对;背景色:绿色;过滤器:alpha(不透明度=60);不透明度:0.6;}跨度{颜色:白色;过滤器:alpha(不透明度=100);不透明度:1;}<p><span>你好,世界</span></p>

看起来子元素受到其父元素的不透明度的影响,因此不透明度:1相对于父元素的不可见性:0.6。


当前回答

当使用#AARGGBB格式时,它对我有效,因此对我有效的格式是#1C00ff00。试试看,因为我看到它对某些人有效,而对其他人无效。我在CSS中使用它。

其他回答

我同意以上所有的答案,rgba是正确的选择。在我的例子中,我以编程方式提供了一个十六进制背景,因此我必须基于十六进制代码生成自己的rgba。我创建了唐先生答案的修改版本,将十六进制转换为rgba

function hexToRgba(hex,alpha) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
      return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    if(result!=null){
      const r = parseInt(result[1], 16);
      const g = parseInt(result[2], 16);
      const b = parseInt(result[3], 16);
      //
      return `rgba(${r},${g},${b},${alpha})`;

    }
    return null;
  }
<div align="center" style="width:100%;height:100%;background:white;opacity:0.5;position:absolute;z-index:1001">
    <img id="search_img" style="margin-top:20%;" src="../resources/images/loading_small.gif">
</div>

http://jsfiddle.net/x2ukko7u/?

使用半透明PNG或SVG图像或使用CSS:

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

这是一篇来自css3.info、Opacity、RGBA和妥协(2007-06-03)的文章。

注意,一旦底层背景穿透,文本仍然需要与背景形成足够的对比。


<p style=“背景色:rgba(255,0,0,0.5);”><span>你好,世界</span></p>

当使用#AARGGBB格式时,它对我有效,因此对我有效的格式是#1C00ff00。试试看,因为我看到它对某些人有效,而对其他人无效。我在CSS中使用它。

如果你是一个Photoshop爱好者,你也可以使用:

 #some-element {
  background-color: hsla(170, 50%, 45%, 0.9); // **0.9 is the opacity range from 0 - 1**
 }

Or:

#some-element {
  background-color: rgba(170, 190, 45, 0.9); // **0.9 is the opacity range from 0 - 1**
}