5

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/

user2738640
  • 1,207
  • 8
  • 23
  • 34

2 Answers2

12

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.

BenM
  • 52,573
  • 26
  • 113
  • 168
4

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.

Paulie_D
  • 107,962
  • 13
  • 142
  • 161