If this has been asked before I sincerely apologize. After around half an hour of searching I cannot seem to find one "best answer," and most solutions I have come across seem to involve JavaScript. While I am not totally opposed to JavaScript - HTML, CSS, and PHP are definitely my stronger skillsets. If this cannot be done without using JavaScript, I will probably need some serious baby talk. Here's my question:
I would like to change the background image of an one element as the hover state of an entirely separate element. Here is an example of how I would like this to work:
.some_element:hover {
#some_unrelated_div {
background-image: url('path/to/img.jpg');
}
}
I hope that conveys a clear enough message of my ideal solution. Thanks guys.
CSS cannot accomplish this. CSS is meant to be read line-by-line and very quickly, so logic isn't something that should be done in CSS.
That being said, you can do this:
.some_element:hover #child_div {
background-image: url('path/to/img.jpg');
}
Iff your HTML is similar to this:
<div class="some_element">
<div id="child_div">Hello</div>
</div>
This works because the selector matches the #child_div
belonging to a :hover
ed .some_element
.
If you plan on using jQuery, this skeleton code will accomplish the job:
$('#trigger').hover(function() {
$('#some_element').css('background-image', 'url("foo.png")');
}, function() {
$('#some_element').css('background-image', 'url("bar.png")');
});
This can be done in pure CSS but only if the element that you wish to change the background image of is a child of the element you are hovering over. For example:
#element1:hover #element2 {
background-image: ...
}
If it is not a child then you will need JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With