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}
Hueij
June 13, 2011, 9:07pm
2
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
force
June 13, 2011, 9:16pm
3
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”.
Hueij
June 13, 2011, 9:22pm
4
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.
Hueij
June 13, 2011, 9:38pm
5
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
The first one should work, the second one won’t, because it will still target the first <a> in each sub-menu list item.
force
June 13, 2011, 10:36pm
7
I tend to avoid the :first-child selector unless really necessary. It’s not supported very well in IE.