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

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

尝试时:

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

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


当前回答

如果你是一个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**
}

其他回答

最好使用半透明.png。

只需打开Photoshop,创建一个2x2像素的图像(选择1x1可能会导致Internet Explorer错误!),用绿色填充,并将“图层选项卡”中的不透明度设置为60%。然后保存它并使其成为背景图像:

<p style="background: url(green.png);">any text</p>

当然,它很酷,除了在可爱的InternetExplorer6中。有更好的修复方法可用,但这里有一个快速破解方法:

p {
    _filter: expression((runtimeStyle.backgroundImage != 'none') ? runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+currentStyle.backgroundImage.split('\"')[1]+', sizingMethod=scale)' : runtimeStyle.filter,runtimeStyle.backgroundImage = 'none');
}

最简单的方法是使用半透明背景PNG图像。

如果需要,可以使用JavaScript使其在InternetExplorer6中工作。

我使用Internet Explorer 6中透明PNG中概述的方法。

除此之外,您可以使用两个并排的兄弟元素来伪装它-使一个半透明,然后将另一个绝对放置在顶部。

不久前,我在Cross Browser Background Transparency With CSS中写到了这一点。

奇怪的是,InternetExplorer6将允许您使背景透明,并使顶部的文本完全不透明。对于其他浏览器,我建议使用透明的PNG文件。

我通常在工作中使用这门课。很好。

.透明{过滤器:alpha(不透明度=50);/*Internet Explorer*/-khtml不透明度:0.5;/*KHTML和旧Safari*/-moz不透明度:0.5;/*Firefox和Netscape*/不透明度:0.5;/*Firefox、Safari和Opera*/}

我认为这将为您提供所需的输出:

div {
  width: 200px;
  height: 200px;
  display: block;
  position: relative;
}

div::after {
  content: "";
  background: url(image.jpg);
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}