DIV中的背景图像透明度

Jan*_*nis 4 css transparency background-image css3

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

background: url(image.jpg) no-repeat center center / cover;
opacity: 0.2;
Run Code Online (Sandbox Code Playgroud)

得到了图像,但DIV中的所有内容都是透明的.我已经搜索了一个解决方案,但似乎无法实现正确的解决方案.关于如何修复它的任何指针?

Sti*_*ers 10

您可以使用CSS linear-gradient()使用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;
}
Run Code Online (Sandbox Code Playgroud)
<div><span>Hello world.</span></div>
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

说明:

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

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

  • Together:background: linear-gradient(...), url(...);创建多个背景,其中两个堆叠,第一个覆盖第二个.


juk*_*ben 7

在包装元素内部的背景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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="page">
  My page
  <div class="box">Red box</div>
</div>
Run Code Online (Sandbox Code Playgroud)