具有较低不透明度的背景而不影响内容(并且不使用伪元素)

时间:2016-03-17 13:04:52

标签: html css css3

如何在不影响<p>

的内容的情况下获得背景图像不透明度0.5
<div class="div_with_background_image">
    <p>content</p>
</div>

问题是:是否有可能这样做?

编辑:

以下是我目前的情况,可以看出opacity正在影响p的内容。

&#13;
&#13;
div {
  background-image: url("http://biendansmacuisine.com/wp-content/uploads/2013/04/2013-04-02-21.29.15.jpg");
  opacity: 0.5;
  height: 500px;
  background-repeat: no-repeat;
}
p {
  background: red;
  width: 200px;
  height: 200px;
}
&#13;
<div>
  <p>
    content with non opatity
  </p>
</div>
&#13;
&#13;
&#13;

请参阅https://jsfiddle.net/6nw6cezb/

2 个答案:

答案 0 :(得分:2)

你可以通过在图像顶部放置一个只有一层半透明白色(alpha = 0.5)的]图像来完成它(不使用任何伪元素或额外元素)。

这也不会影响linear-gradient标记的内容,因为它仍然只是一个背景图片图层,仅此而已。请注意,实际背景图像应在渐变层之后给出,因为CSS将最后一个(在逗号分隔列表中)呈现为最下层。

&#13;
&#13;
p
&#13;
.div_with_background_image {
  background:  linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)),
               url(http://placeimg.com/400/400/animals);
  height: 400px;
  width: 400px;
}
p {
  background: red;
  width: 200px;
  height: 200px;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您想为背景提供透明度,可以使用伪元素:

&#13;
&#13;
.div_with_background_image {
  height: 100px;
  width: 100px;
  position: relative;
}
.div_with_background_image:after {
  background: url(http://www.animalclan.com/blog/wp-content/uploads/2015/06/noticias_48_1390596377.jpg) no-repeat center center / cover;
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  opacity: 0.5;
}
&#13;
<div class="div_with_background_image">
  <p>content</p>
</div>
&#13;
&#13;
&#13;

注意3件事:

  1. pseudoelement必须具有绝对定位。
  2. pseudoelement有z-index:-1。
  3. 您要为该背景提供的元素必须具有位置:relative。