Search code examples
csslistnestedparent

CSS Hover on parent list Item only


So I have some nested lists (only one level deep) and I'm running into trouble with the CSS :hover feature. I only want the hover to apply to the parent class, but I can't figure that one out.

Here's my CSS

<style type="text/css" media="screen">
.listblock li img {
   visibility: hidden;   
}  
.listblock li:hover img {
   visibility: visible;
} 
</style> 

And here is a sample of one of the lists.

<ul>
    <li>One <a href="#"><img src="img/basket.png" height="16" width="16" alt="Buy" class="buy" onClick="pageTracker._trackEvent('Outbound Links', 'Amazon');"/></a></li>
    <li>Two <a href="#"><img src="img/basket.png" height="16" width="16" class="buy" /></a>
        <ul>
            <li>Uno<a href="#"><img src="img/basket.png" height="16" width="16" class="buy" /></a></li>
            <li>Dos <a href="#"><img src="img/basket.png" height="16" width="16" class="buy" /></a></li>
        </ul>
    </li>
    <li>Three <a href="#"><img src="img/basket.png" height="16" width="16" alt="Buy" class="buy" onClick="pageTracker._trackEvent('Outbound Links', 'Amazon');"/></a></li>
</ul>

The problem is that the image in the Uno and Dos list items also hovers. :(

Help please! Thanks a lot


Solution

  • You can use the child selector >, like this:

    .listblock > ul > li:hover img {
       visibility: visible;
    } 
    

    It's not in your pasted code, so this assumes your <ul> is immediately wrapped by a class="listblock" item, if there's something else in-between just add it in with the same format. This selects only the direct child <il> that's a direct child of a <ul> that's a direct of .listbox, so it won't work on the <li> elements further down.