Tony Bogdanov
Tony Bogdanov

Reputation: 7696

Apply CSS to any element except for certain class descendants?

Is it possible to apply certain CSS to any element, except descendants of a certain class?

Here's a fiddle: http://jsfiddle.net/68jgdthm

As you can see I want everything on the page to be dark except elements which are descendants of the light class. The trick here is that one can't know if the element is a direct descendant, e.g. it might be this:

<div class="light">
  <p>Element</p>
</div>

but it might also be this:

<div class="light">
  <div>
    <div>
      <p>Element</p>
    </div>
  </div>
</div>

The dark class is almost always added to the body element and will always be a parent of any light classes.

One might say:

Upvotes: 3

Views: 2303

Answers (2)

Sampsa
Sampsa

Reputation: 711

Color is an inherited property. Therefore just by declaring .dark and .light to have the wanted color is a good thing. You can make a default by assigning it to the body. I think atomic design like this is a good practice, as you don't add too much specificity in your CSS.

You could do this:

body {
    color: #ccc;
}
.dark {
    color: #000;
}
.light {
    color: #fff;
}

Demo: http://jsfiddle.net/68jgdthm/1/

Upvotes: 2

BoltClock
BoltClock

Reputation: 724402

You will not be able to exclude descendants this way without writing a separate selector. You won't be able to do this even using :not(), for the reasons stated here.

Fortunately, the fact that .light elements will only ever occur within the context of a .dark element and not vice versa makes this a little easier. Since you have a body CSS rule already, just add .light p to that rule, and move the entire ruleset underneath .dark p so .light p will take precedence:

.dark p {
    color: #000;
}

body, .light p {
    color: #ccc;
}

Updated fiddle

Alternatively if you want to keep the body rule on top, you could bump up the specificity of .light p to ensure it will take precedence:

body, body .light p {
    color: #ccc;
}

.dark p {
    color: #000;
}

Upvotes: 2

Related Questions