Reputation: 3514
I have a div with a background image inside another div and what I'm trying to achieve is changing that child div's background image when someone hovers anywhere over the entire parent div.
How would I achieve this?
The HTML is like:
<div class="parent_div">
<div class="child_div">
</div>
</div>
And the background image of the child div is:
.child_div{
background-image: url("image.jpg");
}
I tried:
.child_div:hover{
background-image: url("image-new.jpg");
}
But that changes the background only when it's hovered over the child div and since the parent div has some extra padding that I'd like to include, it's not working :(
Upvotes: 0
Views: 946
Reputation: 24559
Here's a runnable snippet, showing you how the css Descendant selector would work:
.parent_div{
height:400px;
width:100%;
background:red;
}
.child_div {
height:200px;
width:100%;
background-image: url(http://placekitten.com/g/200/200); /*initial*/
}
.parent_div:hover .child_div{
background-image: url(http://placekitten.com/g/200/400); /*when parent is hovered*/
}
<div class="parent_div">
<div class="child_div">
</div>
</div>
It's using the css selector:
.parent_div:hover .child_div{
background:...
}
which means when the parent is hovered (red area in snippet), add the styling to the class of child_div as ...
This is because it is using the Descendant selector to select the class .child_div who has a hovered .parent_div element. (other css selectors can be found in the W3C spec)
Upvotes: 4
Reputation: 21
.child_div{
background-image: url("image.jpg");
}
.parent_div:hover .child_div{
background-image: url("new_hovered_image.jpg");
}
You can see more useful selectors here
Upvotes: 0
Reputation: 2967
It should be
.parent_div:hover .child_div{
background-image: url("image-new.jpg");
}
Basically it means: when .parent_div is hovered, .child_div background will be the new image
Upvotes: 3
Reputation: 1639
.parent_div{
width: 200px;
height: 200px;
background: blue;
}
.parent_div:hover .child_div{
background: red;
}
.child_div{
width: 200px;
height: 100px;
}
Example jsfiddle here:
http://jsfiddle.net/9uu9j220/1/
Upvotes: 0
Reputation: 93
Try this css:
.parent {
width: 150px;
height: 150px;
}
.parent img.child {
width: auto; /* or 100% */
height: auto; /* or 100% */
background-image: url('old-bkg.png');
}
.parent img.child:hover{
background-image: url('new-bkg.png');
}
Upvotes: 0
Reputation: 2576
As you tagged your question with JQuery You can try this :
$(document).ready(function(){
$('.parent_div').hover(function(){
$('.child_div').css('background-image','url(urImg.jpg)');
});
});
Upvotes: -1
Reputation: 4578
You are writing an style for child element, but you need to do it for parent:
.parent_div .child_div{
background-image: url('image.jpg');
}
.parent_div:hover .child_div {
background-image: url('image-new.jpg');
}
Upvotes: 0