GSto
GSto

Reputation: 42350

CSS, only affect the top lis of a ul?

I have a nested UL navigation list, with ul's contained inside some other li elements. here's the mark up:

<ul class="navigation">
  <li><a href="#">No Chidren</a></li>
  <li><a href="#">With Chilren</a>
      <ul>
        <li><a href="#">Child 1</a></li>
        <li><a href="#">Child 2</a></li>
      </ul>
  </li>
</ul>

I tried styling it with some of the following CSS declarations:

.navigation { 
 //stylings
}

.navigation li{ 
 //stylings
}

.navigation li a{ 
 //stylings
}

.navigation li a:hover{ 
 //stylings
}

but the .navigation li affects all of the list elements, including the children. is there a way to target the lis so that the styles are only applied to the top-level ones, and not the children?

Upvotes: 2

Views: 3642

Answers (3)

bdukes
bdukes

Reputation: 155955

As others have mentioned, the > selector will only select direct children. However, this doesn't work in IE 6.

If you need to support IE 6, you can add a class to child uls or lis, and use that to remove the styling cascading from the top li:

<ul class="navigation">
  <li><a href="#">No Chidren</a></li>
  <li><a href="#">With Chilren</a>
      <ul class="level1">
        <li><a href="#">Child 1</a></li>
        <li><a href="#">Child 2</a></li>
      </ul>
  </li>
</ul>

--

.navigation li{ 
    background: url(bg.png);
}

.navigation .level1 li{ 
    background: none;
}

Upvotes: 6

mx0
mx0

Reputation: 7133

Yes, it is possible with child selectors.

.navigation>li>a{ 
 //stylings
}

Code above will affect "No Chidren" and "With Chilren" link but not "child 1" element.

Here is working example: http://jsfiddle.net/VuNwX/

And here you can read more about selectors: http://css.maxdesign.com.au/selectutorial/index.htm

Upvotes: 0

John Hartsock
John Hartsock

Reputation: 86882

Like this, the ">" states that the li must be a direct child of .navigation

.navigation { 
 //stylings
}

.navigation > li{ 
 //stylings
}

.navigation > li a{ 
 //stylings
}

.navigation > li a:hover{ 
 //stylings
}

Upvotes: 4

Related Questions