tags:

views:

1296

answers:

4

I have a hierarchical navigation menu in my sidebar that uses nested lists (<ul> and <li> tags). I am using a pre-made theme which already has styles for list items, but I want to alter the style for the top-level items but NOT have it apply to the sub-items. Is there an easy way to apply styles to the top-level list item tag WITHOUT having those styles cascade down to its children list items? I understand that I can explicitly add overriding styles to the sub-items but I'd really like to avoid having to duplicate all of that style code if there is an easy way to just say "apply these styles to this class and DO NOT cascade them down to any children elements". Here is the html I'm using:

<ul id="sidebar">
  <li class="top-level-nav">
    <span>HEADING 1</span>
    <ul>
      <li>sub-heading A</li>
      <li>sub-heading B</li>
    </ul>
  </li>
  <li class="top-level-nav">
    <span>HEADING 2</span>
    <ul>
      <li>sub-heading A</li>
      <li>sub-heading B</li>
    </ul>
  </li>
</ul>

So the css has styles for "#sidebar ul" and "#sidebar ul li" already, but I'd like to add additional styles to "#sidebar .top-level-nav" that do NOT cascade down to its subchildren. Is there any way to do this simply or do I need to rearrange all of the styles so the styles that were on "#sidebar ul" are now specific to certain classes.

A: 

just set them back to their defaults in the "#sidebar ul li" selector

Matthew Vines
Thanks for the answer. Yes I understand that I can set them back in the sub-item's style, but I'm trying to avoid that because I'm using a theme that I didn't create and I'm wondering if I can save a bunch of time by just using some "do-not-cascade: true" rule or something like that, instead of locating all the different styles for the ul's and li's which are scattered all over the place and then worrying about unintended consequences in other areas of the site.
+1  A: 

You either use the child selector

So using

#parent > child

Will make only the first level children to have the styles applied. Unfortunately IE6 doesn't support the child selector.

Otherwise you can use

#parent child child

To set another specific styles to children that are more than one level below.

Silviu Postavaru
+4  A: 

As of yet there are no parent selectors (or as Shaun Inman calls them, qualified selectors), so you will have to apply styles to the child list items to override the styles on the parent list items.

Cascading is sort of the whole point of Cascading Style Sheets, hence the name.

Scott
A: 

You could use something like jQuery to "disable" this behaviour, though I hardly think it's a good solution as you get display logic in css & javascript. Still, depending upon your requirements you might find jQuery's css utils make life easier for you than trying hacky css, especially if you're trying to make it work for IE6

Knowledgethoughts