2014-09-29 56 views
2

我想在背景圖像上使用不透明度,但如果我使用它,它會影響文本。如何在不影響文字的情況下在背景圖片上使用不透明度?

.content_wrapper{ 
width:320px; 
height:374px; 
color:black; 
background-image: url('../images/beuningse-boys-midden.png'); 
background-size:130px; 
background-repeat: no-repeat; 
background-position-x: 95px; 
background-position-y: 155px; 

} 
+2

示例 - '背景色: rgba(0,0,0,0.5);' – Vucko 2014-09-29 07:59:45

+1

可以按照以下鏈接進行回答: - http:/ /stackoverflow.com/questions/7241341/can-i-set-an-opacity-only-to-the-background-image-of-a-div – Puneet 2014-09-29 08:02:12

+0

這是一個很好的問題,我認爲它太多了。但我沒有一個合適的答案。我使用兩個'div'來實現它。一個包含內容文本,另一個包含背景圖像。 – 2014-09-29 08:03:14

回答

1

您不能用CSS更改background-image的不透明度。但是,有辦法達到同樣的結果。

Method 1

此方法使用:這是絕對定位其父內部僞類後。在僞元素上設置背景圖像以及不透明度,使背景不透明度設置在背景上。

HTML

<div> 
    Text on top, no big deal, no big deal. Just a little text and stuff. That's all. 
</div> 

CSS

div { 
    width:320px; 
    height:374px; 
    display: block; 
    position: relative; 
    border: solid 1px #f00; 
} 

div::after { 
    content: ""; 
    background-image: url('http://placehold.it/800x600'); 
    background-size: cover; 
    background-repeat: no-repeat; 
    opacity: 0.5; 
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0; 
    position: absolute; 
    z-index: -1; 
} 


Method 2

如果您需要向後兼容性,您需要在您的標記額外的元素來達到同樣的結果:

HTML

<div class="container"> 
    <div class="background"></div> 
    Text on top, no big deal, no big deal. Just a little text and stuff. That's all. 
</div> 

CSS

.container { 
    width:320px; 
    height:374px; 
    display: block; 
    position: relative; 
    border: solid 1px #f00; 
} 

.container .background { 
    content: ""; 
    background-image: url('http://placehold.it/800x600'); 
    background-size: cover; 
    background-repeat: no-repeat; 
    opacity: 0.5; 
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0; 
    position: absolute; 
    z-index: -1; 
} 

這裏是一個偉大的文章,以達到相同的結果的CSS3方法:

http://css-tricks.com/snippets/css/transparent-background-images/

0

給文本一個類或一個id並給它一個沒有不透明的顏色。

p { 
    color: rgb(120,120,120); // use here what color you want 
} 
相關問題