3

I have a menu list as below:

<div id="menubar">
    <ul class="menulist">
        <li><a href="#">Home</a></li>
        <li><a href="#">Products</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</div>

What I'm trying to do is that initially, the font-color for the menu items is dark grey. But when user hovers over any menu item, that particular item remains dark grey but rest of the items turn light-grey.

I have following CSS.

    #menubar a {
        color: #202021;
        display: block;
        padding: 6px;
        text-decoration: none;
    }

    #menubar a:hover {
        display: block;
        padding: 6px;
        background-color: #97979B;
        border-radius: 3px;
        font-weight: bold;
    }

    #menubar .menulist:hover {
        color: #747478;
    }

But color given in .menulist:hover is not applied to menu items other than hovered item, while properties other than color is applied to rest of the menu items when I hover on any menu item. I followed this SO question which had somewhat similar requirement.

How can I get this behavior with pure CSS?

Community
  • 1
  • 1
Kushal
  • 3,112
  • 10
  • 50
  • 79

1 Answers1

4

Change your two selectors as follows:

#menubar .menulist:hover  a {
    color: #747478;
}​

#menubar .menulist:hover a:hover {
    display: block;
    padding: 6px;
    background-color: #97979B;
    border-radius: 3px;
    font-weight: bold;
}

DEMO


A quick word on the second selector #menubar .menulist:hover a:hover:

Normally, this is only necessary to apply your css because you don't change the color of the anchor when a:hover:

#menubar .menulist:hover a {
    color: #747478;
}​

#menubar a:hover {
    ...
    /* no color change here */
}

If you decide to change the color of the anchor that is hovered though, it will not be applied because the selector #menubar .menulist:hover a has a higher specificity than #menubar a:hover

Example

Making the second selector #menubar .menulist:hover a:hover ensures it has a higher specificity than #menubar .menulist:hover a and rules overrides correctly

Example

Further reading:

Didier Ghys
  • 30,396
  • 9
  • 75
  • 81