2017-01-15 141 views
2

我正在尝试使背景图像透明(无法使透明PNG或更亮的图像,图像经常更改)。DIV中的背景图像透明度

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

得到的图像工作,但DIV内的一切都是透明的。我已经在寻找解决方案,但似乎无法实施正确的解决方案。任何指针如何解决这个问题?

+0

集,用于'容器:背景色:RGBA(0,0,0,0.5);'和清晰混浊 – Khoshtarkib

回答

4

在包装元素的背景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>

+0

不得不使用 'z-index:-0;' 使它工作...但它做了工作!谢谢。 –

2

您可以使用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; 
 
}
<div><span>Hello world.</span></div>

jsFiddle

说明:

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

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

  • 合:background: linear-gradient(...), url(...);创建多个背景,它们中的两个堆叠的,第一个覆盖第二。

+0

这不就是让图像上方的白色透明吗? – Ced

+0

这是否会对浏览器呈现造成更多或更少的压力? –

+0

@JanTeunis我认为任何东西都不会引人注意,因为它是非常标准的CSS3东西,如果你愿意,你可以做一些测试。在[MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds)上了解更多信息。 – Stickers

1

可以使用伪ELEM

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>

+0

不得不使用 'z-index:-0;' 使它工作...但它做了工作!谢谢。 –