如何使用CSS为文本或图像提供透明背景?

如何使用CSS为文本或图像提供透明背景?

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

我想在不将文本和背景作为两个单独元素的情况下实现此目的。

尝试时:

p {

  position: absolute;

  background-color: green;

  filter: alpha(opacity=60);

  opacity: 0.6;

}


span {

  color: white;

  filter: alpha(opacity=100);

  opacity: 1;

}

<p>

  <span>Hello world</span>

</p>

看起来子元素受父母的不透明度影响,因此opacity:1相对于opacity:0.6父元素而言。



茅侃侃
浏览 812回答 3
3回答

宝慕林4294392

这是我能想到的最好的解决方案,而不是使用CSS 3.就我所见,它在Firefox,Chrome和Internet Explorer上运行良好。将容器DIV和两个子DIV放在同一级别,一个用于内容,一个用于背景。使用CSS,自动调整背景大小以适应内容,并使用z-index将背景实际放在后面。&nbsp;.container {&nbsp; &nbsp; &nbsp; position: relative;&nbsp; &nbsp; }&nbsp; &nbsp; .content {&nbsp; &nbsp; &nbsp; position: relative;&nbsp; &nbsp; &nbsp; color: White;&nbsp; &nbsp; &nbsp; z-index: 5;&nbsp; &nbsp; }&nbsp; &nbsp; .background {&nbsp; &nbsp; &nbsp; position: absolute;&nbsp; &nbsp; &nbsp; top: 0px;&nbsp; &nbsp; &nbsp; left: 0px;&nbsp; &nbsp; &nbsp; width: 100%;&nbsp; &nbsp; &nbsp; height: 100%;&nbsp; &nbsp; &nbsp; background-color: Black;&nbsp; &nbsp; &nbsp; z-index: 1;&nbsp; &nbsp; &nbsp; /* These three lines are for transparency in all browsers. */&nbsp; &nbsp; &nbsp; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";&nbsp; &nbsp; &nbsp; filter: alpha(opacity=50);&nbsp; &nbsp; &nbsp; opacity: .5;&nbsp; &nbsp; }<div class="container">&nbsp; <div class="content">&nbsp; &nbsp; Here is the content.&nbsp; &nbsp; <br />Background should grow to fit.&nbsp; </div>&nbsp; <div class="background"></div></div>
打开App,查看更多内容
随时随地看视频慕课网APP