Sylvain
Sylvain

Reputation: 19269

CSS Selector for all descendants excluding nested instances

I have a question related to Select first Descendant with CSS or How do I hide only the first element of a type? but my case doesn't match these ones.

I need to target all .page descendants of class .example but excluding nested .example.

In this example, I'd like to target only #h1-a and #h1-c:

<div class="page">
  <!-- there could be many levels of wrapping -->
  <div>
    <div>
      <div id="h1-a" class="example">
        <h1>h1-a</h1>
        <div>
          <div id="h1-b" class="example">
            <h1>h1-b (nested)</h1>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- or there could be none -->
  <div id="h1-c" class="example">
    <h1>h1-c</h1>
    <div>
      <div id="h1-d" class="example">
        <h1>h1-d (nested)</h1>
      </div>
    </div>
  </div>
</div>

Here is a jsfiddle to get us started.

Upvotes: 1

Views: 534

Answers (1)

Rounin
Rounin

Reputation: 29493

You can use the CSS cascade to overwrite an earlier rule (applying to a more general context) with a later rule (applying to a more specific context):

.page .example {
border: 1px solid rgb(127,127,127);
}

.page .example .example {
border: none;
}

This is exactly how the CSS cascade is supposed to work - general rules higher up, specific exceptions lower down.

Upvotes: 3

Related Questions