2016-07-02 29 views
1

我有一個div背景圖像,我使用過濾器以黑白顯示(filter: grayscale(100%);)。我現在試圖在該div內放置一個顏色圖標。試圖將圖標設置爲grayscale(0%),但這似乎不起作用。灰度(100%)容器內的彩色圖像

下面是一個例子:

#a1, #a2 { 
 
    background-image: url(http://ndrichardson.com/blog/wp-content/uploads/2012/04/colorpsychology.jpg); 
 
    background-repeat: no-repeat; 
 
    background-size: 100% 100%; 
 
} 
 
#a1 { 
 
    height: 250px; 
 
    width: 250px; 
 
    -webkit-filter: grayscale(100%); 
 
    filter: grayscale(100%); 
 
    position: relative; 
 
} 
 
#a2 { 
 
    height: 50px; 
 
    width: 50px; 
 
    -webkit-filter: grayscale(0%); 
 
    filter: grayscale(0%); 
 
    position: absolute; 
 
    top: 0px; 
 
    right: 0px; 
 
}
<div id="a1"><!-- << this should be black and white --> 
 
    <div id="a2"><!-- << this should be color --> 
 
    </div> 
 
</div>

有沒有辦法做到這一點,而無需創建一個額外的div來容納背景圖像?真正的代碼要複雜得多,這就是爲什麼我想避免多餘的div(如果可能的話)。

回答

3

當然是的,你應該使用::before::after僞元素:

#a1 { 
 
    height: 250px; 
 
    width: 250px; 
 
    position: relative; 
 
} 
 
#a1:after, #a1:before { 
 
    content: ''; 
 
    background-image: url(http://ndrichardson.com/blog/wp-content/uploads/2012/04/colorpsychology.jpg); 
 
    background-repeat: no-repeat; 
 
    background-size: 100% 100%; 
 
    position: absolute; 
 
} 
 
#a1:before { 
 
    -webkit-filter: grayscale(100%); 
 
    filter: grayscale(100%); 
 
    width: 100%; 
 
    height: 100%; 
 
} 
 
#a1:after { 
 
    height: 50px; 
 
    width: 50px; 
 
    top: 0px; 
 
    right: 0px; 
 
}
<div id="a1"></div>

DEMO on JSFiddle

3

這是不可能有一個容器內的顏色與filter: grayscale(100%)

the filter property在規範(重點煤礦):

的以外none結果的計算值在創建的 stacking context同樣的方式,CSS opacity一樣。所有 元素後代都作爲一組呈現在一起 過濾器效果作爲整體應用於組

所以是的,你將不得不從內容中分離內容與過濾器沒有它。

這並不一定意味着您需要HTML中的其他包裝,因爲Hiszpan建議您也可以使用僞元素。