tylerl
tylerl

Reputation: 1180

CSS - Manipulate another element on hover

I need to change #hidden to display:block when #aaa is hovered over. It's not working because #aaa isn't on the same level as #hidden - is there a way to manipulate a completely separate element on hover? I'm trying to make a CSS-based nav w/ a subnav and show the respective subnav when a nav item is hovered over.

HTML:

<div class="cheetahContainer">
    <div id="cheetah">
       <p><a href="#">Cheetah</a></p>
    </div>
</div>
<div id="hidden">
       <p>A cheetah is a land mammal that can run up 2 60mph!!!</p>
</div>

CSS:

#cheetah {
    background-color: red;
    text-align: center;
}

a {
    color: blue;
}

#hidden {
    display:none;
    color: orange;
 }
#cheetah:hover{
    background-color:green;
}

#cheetah:hover + #hidden {
    display:block;
}

http://jsfiddle.net/LgKkU/575/

Upvotes: 0

Views: 499

Answers (3)

Hive7
Hive7

Reputation: 3675

It is not a direct sibling so you need to use js

Here is an example of what to do:

var $cheetah = document.getElementById('cheetah');
var $hidden = document.getElementById('hidden');
$cheetah.addEventListener('mouseover', function() {
    $hidden.style.display = 'block';
});
$cheetah.addEventListener('mouseout', function() {
    $hidden.style.display = 'none';
});

Or you can use the container:

.cheetarContainer:hover + #hidden {
    display: block;
}

Upvotes: 0

maxm
maxm

Reputation: 3667

Hovering over an element can only affect child elements in css. Here's a fix for your example:

<div class="cheetahContainer">
    <div id="cheetah">
       <p><a href="#">Cheetah</a></p>
    </div>
    <div id="hidden">
           <p>A cheetah is a land mammal that can run up 2 60mph!!!</p>
    </div>
</div>

However, I would recommend changing the css to something like this:

.cheetahContainer:hover .hidden {
  display: block;
}

Changed out id's for classes and added hover to parent element so that hovering over the revealed text doesn't revert back to display:none;

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

Since your link is not a sibling of your #hidden div (thus you can't use the immediate adjacency selector), you should change last rule with

.cheetahContainer:hover + #hidden {
    display:block;
}

Upvotes: 1

Related Questions