Only apply style to the descendents of the first-child of named element?

I’ve got a nested unordered list in which I want to isolate some css rules so that they only apply to hyperlinked elements that are direct descendents of the parent UL element.

I don’t want any of these rules to apply to anchors that are descendent elements.

For example, my markup is:

<div class="menu nav">
	<ul class="menu">
		<li class="menu-item"><a href="#">Home</a></li> 
		<li class="menu-item"><a href="contact-us">Contact Us</a></li> 
		<li class="menu-item"><a href="about-us">About Us</a> 
			<ul class="sub-menu"> 
				<li class="menu-item"><a href="privacy-policy">Privacy Policy</a></li> 
				<li class="menu-item"><a href="ftc-disclaimer">FTC “Disclaimer”</a></li> 
			</ul> 
		</li> 
	</ul> 
</div> 

I only want the rules applied to the “Home”, Contact Us, and “About Us” elements.

Here’s what I’ve tried, what am I missing?

.menu.nav ul.menu:first-child li a {//rules here}

What you did is target every anchor in <ul class=“menu”>. What you should do to target only the direct children of this ul:


ul#menu>li a

A great explanation of how this works: The Child Selector

It looks like you’ve already set things up pretty close to that already.

Try using

div.nav li.menu-item a { /*stuff*/ }

And then for the sub menu items, indicate that in the classes. Instead of “menu-item”, use “sub-menu-item”.

Oops! I should have thought about this a minute longer :x With my method you also target the second level anchors. Force Flow’s method should work.

Hm… Some more thinking gave me this:


ul#menu>li>a

or this:


ul#menu>li a:first-child

Maybe I should go to bed :frowning:

The first one should work, the second one won’t, because it will still target the first <a> in each sub-menu list item.

I tend to avoid the :first-child selector unless really necessary. It’s not supported very well in IE.