How do I prevent CSS inheritance?

Viewed 153874

I have a hierarchical navigation menu in my sidebar that uses nested lists (<ul> and <li> tags). I am using a pre-made theme that 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 sub-children. 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?

13 Answers

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.

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.

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

You can wrap the element that you don't want to inherit any styles in a div with no style.

Something like this:

<div style='all: revert !important;'>
  Your content here
</div>

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

here's an live example using cascade, initial and all property:

div {
  border: 1px solid red;
  margin: 10px;
}

div p {
  color: red;
}

.initial {
  border-color: initial;
}

.initial p {
  color: initial;
}

.asterisk,
.asterisk * {
  border-color: initial;
  color: initial;
}

.all,
.all * {
  all: initial
}

https://jsbin.com/cosabusiwi/1/edit?html,css,output

Related