ClutchHunter
ClutchHunter

Reputation: 27

How to style a parent element when the mouse is over a child element?

Trying to get the top bit of a navbar to change text colour when I hover over any of the listed bits below it.

HTML

<div id="wrapper">
    <div id="navMenu">
        <ul>
            <li><a href="#">Home</a></li>
        </ul>
        <ul>
            <li><a href="#">example1</a>
                <ul>
                    <li><a href="#">example1.1</a></li>
                    <li><a href="#">example1.2</a></li>
                    <li><a href="#">example1.3</a></li>
                    <li><a href="#">example1.4</a></li>
                    <li><a href="#">example1.5</a></li>
                </ul>
            </li>
        </ul>

        <br class="clearFloat" />

    </div> <!-- end navMenu div -->
</div> <!-- end wrapper div -->

CSS

#navMenu {margin:0;padding:0;}
#navMenu ul {margin:0;padding:0;line-height:30px;}
#navMenu li {margin:0;padding:0;list-style:none;float:left;position:relative;background:#999;}
#navMenu ul li a {text-align:center;text-decoration:none;height:30px;width:150px;display:block;color:#060;border:1px solid #666;}
#navMenu ul ul {position:absolute;visibility:hidden;top:32px;}
#navMenu ul li:hover ul {visibility:visible;}
#navMenu li:hover {background:#060;}
#navMenu ul li:hover ul li a:hover {background:#CCC;color:#FFF;}
#navMenu a:hover {color:#FFF;}
.clearFloat {clear:both;margin:0;padding:0;}

Is this possible in pure CSS? If not, how would I easily make this work using Javascript or something else?

Edit: The text turns white when you hover over while the background turns green. The latter remains but the former does not. I think that's the problem.

Upvotes: 1

Views: 106

Answers (1)

Daniel Imms
Daniel Imms

Reputation: 50229

You can't select a parent when you hover a child in CSS, you can only select siblings that come after or descendants.

However, I think you'll be fine with just a hover parent event as when you hover the child the parent is also hovered. Add this:

jsFiddle

#navMenu li:hover a {color:#FFF;}

Upvotes: 4

Related Questions