[英]background color change on hover with background-size
我有以下代碼:
CSS:
<style>
div.testy {
border:1px solid black;
}
div.testy:hover {
background-color:red;
}
</style>
HTML:
<div class="testy" style="height:100px;
background: url('down.png') no-repeat; background-size:contain;">
aa
</div>
'down.png'
是具有透明背景的圖像。 我想做的是改變背景的顏色,同時仍將圖像置於顏色前面。
前面的代碼幾乎可以正確執行所有操作,但是當我將鼠標懸停在div
,什么也沒發生。
問題:為什么懸停和背景顏色更改不起作用?
這是發生問題的jsfiddle鏈接: https ://jsfiddle.net/sdsze2fv/
問題是您正在使用background:
作為"background image"
。 通過分別使用background-color
和background-image
區分background image
和background color
。
div.testy { border:1px solid black; } div.testy:hover { background-color:red; }
<div class="testy" style="height:100px; background-image: url('http://www.w3schools.com/html/html5.gif'); background-size:contain;"> aa </div>
發生這種情況是因為您已經在html中定義了background
內聯。 內聯樣式始終會覆蓋css文件中設置的樣式,除非您在樣式中添加!important
。
我建議您僅以內聯樣式設置background-image
,然后在CSS文件的規則中設置background-color
。
div.testy { border:1px solid black; } div.testy:hover { background-color:red; }
<div class="testy" style="height:100px; background-image: url('down.png'); background-repeat: no-repeat; background-size:contain;"> aa </div>
內聯設置的背景將覆蓋CSS規則中的背景。 內聯樣式始終會覆蓋任何內容(帶有!important的內容除外)。 如果刪除內聯並將其放入規則中,它將起作用。 或這包括另一種方法
在這里,我們說的是“嘿,我希望bkgrnd圖像是這個” ...不是背景...因為背景包括圖像,顏色,重復等的所有內容。它是簡寫形式。 因此,您在技術上也在那里設置bkgrnd顏色...這就是為什么它會懸停在您的上方。
這是另一個選擇...從內聯刪除並放入規則中...按原樣...然后它也可以工作
div.testy {
border:1px solid black;
height: 100px;
font-size: 25px;
color: orange;
background: url('https://upload.wikimedia.org/wikipedia/commons/3/3a/Gluecksklee_(transparent_background)2.png') no-repeat;
background-size: contain;
}
div.testy:hover {
background-color:red;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.