user3915624
user3915624

Reputation:

CSS - affecting an element by hovering on another one, when they both belong to different divs

Is it possible to affect an element that is placed within a div by hovering on an element that belongs to another div?

I can get it to work using the general sibling selector, but only when the element that I hover on isn't placed inside any other element. Is this the only way it can be done?

Edit: I didn't really want to tire you with all the details but yes, perhaps I should have included some markup in the first place. So, here it is, rather (over)simplified:

 <nav>
  <button></button>
 </nav>

<div id="sidemenu">
 <ul class="nav">
  <li>Link 1</li>
  <li>Link 2</li>
 </ul>
</div>

When on small devices, the sidemenu would be hidden and the button element would appear. Hovering on the latter would make the sidemenu reappear as a drop down menu. At least that was the idea. I don't really feel that it would be right to change the markup, so I guess I need to find another way to do this.

Upvotes: 0

Views: 797

Answers (1)

Anwardo
Anwardo

Reputation: 710

This is not possible. You can make a child element respond to a hover on a parent, but it's not possible to make an entirely different element respond to a hover on another random element.

With CSS only that is. It is possible if you add a little javascript/jQuery. You could for instance use the hover function in jQuery.

//edited
$('button').hover(function () {
     $('#sidemenu').addClass('hover');
}, 
function () {
     $('#sidemenu').removeClass('hover');
});  

What this basically does is add a class to #other-element when hovering over #element and removing the class when the hover is removed.

Edit: I updated the code to match your markup. In this case hovering over the button would add a class to the sidemenu. You could then style the sidemenu like this:

 #sidemenu
 {
 display:none;
 }

 #sidemenu.hover
 {
 display:block;
 }

This piece of css would normally hide the #sidemenu but shows it when the class hover is added to it.

Upvotes: 1

Related Questions