Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper CSS to style nested element

Tags:

html

css

I'm working on a CSS dropdown. I would like to be able to add a class active to list elements in my dropdown to show the particular item is the current selection. The problem is, I cannot get the text colour to change. The background does, but not the text...

enter image description here

Demo: http://jsfiddle.net/tMND4/4/

HTML:

<ul class="dropdown">
    <li>
        <a href="#">Nice test items</a>
        <ul class="submenu">
               <li><a href="#">Sonic Screwdriver</a></li>
               <li class="active"><a href="#">TARDIS</a></li>
               <li><a href="#">Long Scarf</a></li>
        </ul>
    </li>
</ul>

CSS:

body{
    padding:10px;
}

.dropdown > li{
    width:200px; /*or anything you want!*/
    color:#333;
    text-decoration:none;
    padding:2px; /*all things wont stick to the side */
}

.dropdown li a{
    display:block;
    color:#666;
    text-decoration:none;
    padding:5px; /*line it up with sublinks */
}

.dropdown li .submenu{
    display:none; /*hide submenu*/
}
/* child selector to prevent style propagation*/
.dropdown > li:hover{
    border:1px solid #666;
}

/* child selector to prevent style propagation*/
.dropdown > li:hover a {
    padding: 4px; /*reduced padding to compensate for border*/
}

.dropdown li:hover .submenu{
    display:block; /*display submenu*/
}

.dropdown li:hover .submenu a{
    display:block;
    padding:5px; /*line it up with links */
}

.dropdown li:hover .submenu a:hover{
    background: #DDD;
}

.active{ 
    background:#666;
    color:#FFF;
}
like image 557
Alex Guerin Avatar asked Jan 06 '12 02:01

Alex Guerin


1 Answers

This is due to specificity. You have to be more specific with your .active selector.

For example:

.dropdown li.active a { 
    background:#666;
    color:#FFF;
}

Here's your fiddle: http://jsfiddle.net/tMND4/5/

like image 194
Joseph Silber Avatar answered Nov 15 '22 08:11

Joseph Silber