user2738640
user2738640

Reputation: 1227

CSS select direct child items only

I have following html markup. I want to apply a css style to the li items which are direct children of main ul. I do not want to select the li items which are nested inside li. How can I do that?

In the following code, I want to select only "main item 1" and "main item 2". I'm trying > operator but it does not work.

HTML:

<div class="nav">
    <ul>
        <li><a>Main item 1</a></li>
        <li><a>Main item 2</a>
            <ul>
                <li><a>sub item 1</a></li>
                <li><a>sub item 2</a></li>
            </ul>
        </li>
    </ul>
</div>

CSS:

.nav > ul li a:hover{
    color: red;
}

Demo: http://jsfiddle.net/tk6RS/

Upvotes: 7

Views: 14254

Answers (2)

Paulie_D
Paulie_D

Reputation: 115285

Just be more specific.

.nav > ul > li > a:hover{
    color: red;
}

To be more precise...

.nav > ul li 

selects ANY li that is within the ul that is the direct child of .nav. This includes li that are within any submenus.

.nav > ul > li 

selects only the li that are direct children of the ul that is the direct child of .nav.

By extension you want to only select the anchors within the selected li (for the same reason as above)....hence the original answer.

Upvotes: 5

BenM
BenM

Reputation: 53238

You're only selecting the parent ul with >, you'll need to add another to also pick immediate children of that ul, for example:

.nav > ul > li > a:hover{
    color: red;
}

You'll also need to add li > a:hover to select the anchor elements inside them, since the child <a> elements are also within the <li> scope.

Upvotes: 14

Related Questions