Graeme
Graeme

Reputation: 175

CSS Hover Menu Showing active menu item

I have the following css:

#nav ul li {float: left; margin-right: 10px; }
#nav ul li a { display: block; color: #fff; width: 100px; line-height:35px; background: #15612e; padding-left:16px;}
#nav ul li a:hover { background-color: #ea8206;}

This works as expected. What I would now like to do is have a class like this:

 a.active { background-color: #ea8206;}

Which I would like to assign to whichever menu item is selected on a page, but this is not working.

I assume it's to do with precedence, and have tried various combinations of:

#nav ul li a.active {background-color: #ea8206;}

I think I am just struggling with the right combination.

And the HTML is:

       <div id="nav">
            <ul>
                <li><a href="#" class="active">Home</a></li>
                <li><a href="#">Buy</a></li>
                <li><a href="#">Sell</a></li>
                <li><a href="#">Search</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </div>

Could anyone point me in the right direction?

Many thanks

Upvotes: 0

Views: 1603

Answers (1)

Pat Dobson
Pat Dobson

Reputation: 3299

Here's a fiddle : http://jsfiddle.net/moonspace/aKLUS/

This is all about specificity... As you've already referred to 'a' classes in the CSS but prefixed them with '#nav ul' these will override a simple 'a.active' definition. So, add the '#nav ul' before a.active (as per the fiddle) and it'll work . . .

#nav ul li a { display: block; color: #fff; width: 100px; line-height:35px; background: #15612e; padding-left:16px;}
#nav ul li a:hover { background-color: #ea8206;}
#nav ul li a.active{ background-color: red; }

More useful stuff here : http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

Upvotes: 1

Related Questions