CSS:背景不透明显示在文本上

时间:2018-08-27 12:04:24

标签: html css opacity

以该代码为例

#backgroundimage {
  background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
  height: 50px
}

#container {
  background-color: #4C4C4C;
  opacity: 0.5;
}

#text {
  color: #ffffff;
  opacity: 1;
}
<div id="backgroundimage">
  <div id="container">
    <p id="text">
      Some text here
    </p>
  </div>
</div>

我想使文本颜色为白色,同时保持背景图像和容器的不透明度。 Look at this image as Reference

3 个答案:

答案 0 :(得分:3)

看看下面的例子。使用opacity代替rgba。 根据{{​​3}}:

  

opacity应用于整个元素,包括元素的内容,即使该值未被子元素继承。因此,该元素及其子元素相对于元素背景具有相同的不透明度,即使它们彼此之间具有不同的不透明度。

#backgroundimage {
  background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
  height: 500px
}

#container {
  background-color: rgba(76,76,76,.5);
}

#text {
  color: #ffffff;
}
<div id="backgroundimage">
  <div id="container">
    <p id="text">
      Some text here
    </p>
  </div>
</div>

答案 1 :(得分:0)

当您设置元素的opacity时,它会影响其子元素(并且,如果您设置了子元素的opacity,则它不能覆盖父元素的opacity

您需要做的不是设置元素的opacity,而是使用rgba仅将不透明度设置为背景。

#backgroundimage {
  background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
  height: 500px
}

#container {
  background-color: rgba(76, 76, 76, 0.5); /* #4C4C4C;*/
  /*opacity: 0.5;*/
}

#text {
  color: #ffffff;
  opacity: 1;
}
<div id="backgroundimage">
  <div id="container">
    <p id="text">
      Some text here
    </p>
  </div>
</div>

答案 2 :(得分:-2)

使背景图像(640x480-aero-solid-color-background.jpg)透明,并将其另存为.png或.gif格式。

从“ #container”类中删除“ opacity:0.5”,从“ #text”类中删除“ opacity:1”

相关问题