Reputation: 7113
I have the following code:
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'
is an image with a transparent background. What I wanted to do was have the color of the background change while still keeping the image in front of the color.
The previous code does almost everything right, except that when I hover the mouse over the div
, nothing happens.
QUESTION: Why might it be that the hovering and the background color change are not working?
Here is a jsfiddle link with the problem happening: https://jsfiddle.net/sdsze2fv/
Upvotes: 1
Views: 2044
Reputation: 4686
The problem is that you are using background:
for the "background image"
. Differentiate background image
and background color
by using background-color
and background-image
respectively.
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>
Upvotes: 3
Reputation: 389
The background you are setting inline is overriding the one in the css rule. Inline styles always override anything (except stuff with !important). If you remove the inline and put it in a rule, it will work. Or another method is included in this
in this we are saying 'hey, i want the bkgrnd image to be this'...not the background...because background includes everything from image, color, repeat etc. Its the shorthand. So you are technically setting the bkgrnd color there too...which is why its over riding your hover.
Here is the other option...remove from inline and put it into the rule...as is....then it also works
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;
}
Upvotes: 0
Reputation: 2631
This happens because you already defined your background
inline in your html.
Inline styles always override styles set in a css file unless you have added !important
to the style.
I recommend that you only set background-image
in your inline style and then background-color
in your rule in the CSS-file.
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>
Upvotes: 1