2012-12-03 46 views
0

我想使用CSS將圖像與純色混合。如何才能做到這一點?如何在CSS中將圖像與純色混合?

這是我到目前爲止有:

header { 
    width: 900px; 
    height: 60px; 
    background-image: url(../images/banner.jpg); 
    background-color: rgba(51,102,153,0.5); 
} 

它不工作雖然!

我只是無法得到我的頭。

感謝您的幫助!

+0

爲什麼不使用(半)透明圖像 - 例如'png'? – Aprillion

+0

,因爲我在另一個地方也使用該圖像,我不想要兩個文件 – Tintin81

+0

圖像是否具有透明背景? – Kyle

回答

3

使用兩個div,見this fiddle

HTML:

<div id="wrapper"> 
    <div id="content"></div> 
</div> 

CSS:

#wrapper 
{ 
    background: url("http://sp9.fotolog.com/photo/41/8/54/butterlyinthebox/1243705008574_f.jpg") no-repeat; 
} 

#content 
{ 
    background-color: yellow; 
    opacity: 0.5; 
    width: 477px; 
    height: 318px; 
} 
+0

工作,謝謝! – Tintin81

+2

我建議不要將內容圖像作爲背景圖像發佈。 – Damien

1

目前公認的答案的作品,但它的語義上不正確,並會從一些優化技術中受益。

你可以使用這個僞後元素,所以你不需要爲此引入額外的標記。所以標記仍然是這樣的:

<div id="content"></div> 

CSS是冗長的,但更具表現力。我不喜歡「包裝器」包含實際內容(圖片),而「內容」只是一個簡單的顏色。也不需要淡入整個div,但是您可以使用alpha通道作爲顏色。

#content { 
    position: relative; 
    background: url("http://sp9.fotolog.com/photo/41/8/54/butterlyinthebox/1243705008574_f.jpg") no-repeat; 
    width: 477px; 
    height: 318px; 
} 
#content:after { 
    content: ''; 
    position: absolute; 
    width: 100%; 
    height: 100%; 
    background-color: rgba(255,0,0,0.5); 
    pointer-events: none; 
} 

​jsfiddle

+0

謝謝!這個確實很高雅。 – Tintin81

6

目前公認的答案,它的替代確實工作。但兩者都使用背景圖像來表示實際內容。該方法使用img標籤。

HTML

<div class="blend"> 
<img src="http://sp9.fotolog.com/photo/41/8/54/butterlyinthebox/1243705008574_f.jpg" alt=" " /> 
</div>​ 

CSS

.blend { 
    background: red; 
    display: inline-block; 
} 

.blend img { 
    opacity: 0.5; 
} 

看到這個fiddle

+0

謝謝,Damien!仍然試驗各種方法來做到這一點...... – Tintin81

+0

謝謝,我需要一個解決方案,使用一個div內的img ... –

+0

現在看看它...這可能是更多的語義與

標籤。 – Damien