Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS select direct child items only

Tags:

html

css

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/

like image 854
user2738640 Avatar asked Jul 14 '26 11:07

user2738640


2 Answers

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.

like image 113
BenM Avatar answered Jul 16 '26 07:07

BenM


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.

like image 24
Paulie_D Avatar answered Jul 16 '26 06:07

Paulie_D