Relevart
Relevart

Reputation: 747

How to disable the effect of a CSS class on a nested element?

Is there a way or woukaround to specify a CSS class in a way that it only affects certain nested elements? In the example let's suppose that the .rich-text class has some CSS rules. I would want to achieve that it applies to everything inside that div except the .inner div and all it's descendants.

<div class="rich-text">
    <div class="random">
        <div class="inner">
            The rich-text class should not effect this or anything in it
        </div>
        <p>Some text...</p>
    </div>
</div>

EDIT: I see that there are some answers that try to give a solution to this exact example code. I would need a general solution that works no matter where the inner class is at (it could be 2 or 20 levels deep and so on...).

Upvotes: 3

Views: 4319

Answers (3)

DavidDomain
DavidDomain

Reputation: 15293

Just set the rules for .inner and all it's descendants back to initial.

.rich-text {
  color:red;
  font-family: sans-serif;
}

.inner, .inner > * {
  color: initial;
  font-family: initial;
}
<div class="rich-text">
  <div class="random">
    <div class="inner">The rich-text class should make no effect on this and everything inside it.<h1>Foo</h1></div>
    <p>Some text...</p>
  </div>
</div>

Upvotes: 2

user494599
user494599

Reputation:

According to your example, you have to use the direct children css selector (and not deeper) :

.rich-text > *

It means the rules are only applied to the direct children of .rich-text.

Upvotes: 0

user3254198
user3254198

Reputation: 759

you can simply write the indexed class name right after the root.

So for example in your case you want inner class to only apply to random which has to be within rich-text.

.rich-text .random .inner {
    color: red;
}

The red text color would only apply to any element with the inner class applied which has to be within a element with a random class which has to be within a element with rich-text class.

This would apply to anything that follows that hierarchy but bare in mind that it doesn't have to be directly following it. Another way to put it is that you can still have a something class inbetween random and rich-text and the red text would still work.

If you want it to be a strict hierarchy then you can simply use > which means that it has to directly follow the given matches.

.rich-text > .random > .inner {
    color: red;
}

Would ONLY apply the red text color if the inner class is within random within rich-text and it has to follow that hierarchy and can't have anything else inbetween

Upvotes: 1

Related Questions