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

CSS : Background opacity is showing on text

以此代码为例

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

我想将文本颜色设为白色,同时保持背景图像和容器不透明度不变。

看看下面的例子。使用 rgba 而不是 opacity。 根据docs:

opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, the element and its children all have the same opacity relative to the element's background, even if they have different opacities relative to one another.

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

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

从“#container”中删除 "opacity: 0.5" class 并从“#text”中删除 "opacity: 1" class

当你设置一个元素的opacity时,它会影响它的children(如果你设置一个child的opacity,它不能覆盖 parent 的 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>