【问题标题】:How do I use opacity on a background image without effecting the text?如何在不影响文本的情况下在背景图像上使用不透明度?
【发布时间】:2014-11-23 13:24:57
【问题描述】:

我正在尝试在背景图像上使用不透明度,但如果我使用它也会影响文本。

.content_wrapper{
width:320px;
height:374px;
color:black;
background-image: url('../images/beuningse-boys-midden.png');
background-size:130px;
background-repeat: no-repeat;
background-position-x: 95px;
background-position-y: 155px;

}

【问题讨论】:

  • 示例 - background-color: rgba(0,0,0,0.5);
  • 希望您可以点击此链接获得答案:- stackoverflow.com/questions/7241341/…
  • 这是个好问题,我想了太多时间了。但我没有合适的答案。我使用两个div 来实现它。一个包含内容文本,另一个包含背景图像。
  • 习惯了这个jsfiddle.net/xb2bk7bp

标签: css background opacity


【解决方案1】:

您无法使用 CSS 更改 background-image 的不透明度。但是,有一些方法可以达到相同的结果。

Method 1

此方法使用 :after 伪类,该伪类绝对位于其父级内部。背景图像与不透明度一起设置在此伪元素上,给人的印象是背景不透明度是在背景本身上设置的。

HTML

<div>
  Text on top, no big deal, no big deal. Just a little text and stuff. That's all.
</div>

CSS

div {
  width:320px;
  height:374px;
  display: block;
  position: relative;
  border: solid 1px #f00;
}

div::after {
  content: "";
  background-image: url('http://placehold.it/800x600');
  background-size: cover;
  background-repeat: no-repeat;
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}


Method 2

如果您需要向后兼容,则需要在标记中添加一个额外的元素来获得相同的结果:

HTML

<div class="container">
    <div class="background"></div>
    Text on top, no big deal, no big deal. Just a little text and stuff. That's all.
</div>

CSS

.container {
  width:320px;
  height:374px;
  display: block;
  position: relative;
  border: solid 1px #f00;
}

.container .background {
  content: "";
  background-image: url('http://placehold.it/800x600');
  background-size: cover;
  background-repeat: no-repeat;
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}

这是一篇很棒的文章,其中包含实现相同结果的 CSS3 方法:

http://css-tricks.com/snippets/css/transparent-background-images/

【讨论】:

    【解决方案2】:

    给文本一个类或一个id,并给它一个不透明的颜色。

    p {
        color: rgb(120,120,120); // use here what color you want
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 2016-12-23
      • 1970-01-01
      • 2017-03-17
      • 2011-06-27
      相关资源
      最近更新 更多