DIV 中的背景图像透明度

Background image transparency in DIV

我正在尝试使背景图像透明(没有制作透明 PNG 或更亮图像的选项,图像经常更改)。

background: url(image.jpg) no-repeat center center / cover;
opacity: 0.2;

得到的图像是有效的,但 DIV 中的所有内容也是透明的。我已经搜索了一种解决方案,但似乎无法实施正确的解决方案。关于如何解决这个问题的任何指示?

在包装元素内部 div 使用背景不透明度。

.page {
  position: relative;
  width: 100px;
  height: 100px;
}
.page::before {
  content: '';
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  background:  url('http://www.visitnorwich.co.uk/assets/Uploads/Events-images/Theatre-generic.jpg');
  opacity: 0.2;
  z-index: -1;
}
.box {
  display: inline;
  background: red;
}
<div class="page">
  My page
  <div class="box">Red box</div>
</div>

您可以使用 CSS linear-gradient() with rgba().

div {
  width: 300px;
  height: 200px;
  background: linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,.5)), url("https://i.imgur.com/xnh5x47.jpg");
}
span {
  background: black;
  color: white;
}
<div><span>Hello world.</span></div>

jsFiddle

解释:

  • 第一部分:linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,.5))创建semi-transparent白色背景色。您可以根据需要在 0(完全透明)和 1(完全不透明)之间更改 alpha 参数。

  • 第二部分:url("https://i.imgur.com/xnh5x47.jpg")显示实际背景图片

  • 一起:background: linear-gradient(...), url(...);创建多个背景,两个叠加,第一个覆盖第二个。

你可以使用伪元素

    div {
      width: 300px;
      height: 200px;
      color: green;
      position: relative;
    }

    div:before{
        background: url(https://i.imgur.com/xnh5x47.jpg);
        content: "";
        z-index: -1;
        position: absolute;
        opacity: 0.5;
        top: 0; bottom: 0; left: 0; right: 0;
        background-size: cover;
     }
<div> LOLOLOL </div>