Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing multiple elements with CSS?

Tags:

javascript

css

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.

like image 822
drewwyatt Avatar asked Dec 06 '11 06:12

drewwyatt


2 Answers

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 :hovered .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")');
});
like image 121
Blender Avatar answered Oct 10 '22 11:10

Blender


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.

like image 42
Dan Avatar answered Oct 10 '22 10:10

Dan