2017-01-15 142 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;' 使它工作...但它做了工作!謝謝。 –