How can I turn off the CSS class effect for a nested element?

Is there a way or woukaround for specifying a CSS class in such a way that it only affects certain nested elements? For the example, let's say the .rich-text class has some CSS rules. What I would like to achieve is that this applies to everything inside this div except the .inner div and all of its 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 there are some answers that try to give a solution for this exact example code. I would need a generic solution that works no matter where the inner class is (it could be 2 or 20 levels, etc.).

+3


source to share


3 answers


you can just write the name of the indexed class right after the root.

So, for example, in your case, you only want the class to inner

apply to random

which should be within rich-text

.

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

      

The red text color is applicable only to any element with an attached class inner

that must be inside an element with a class random

, which must be inside an element with a class rich-text

.



This applies to everything that follows this hierarchy, but with the understanding that it should not directly follow it. Another way is to say that you can still have a class something

between random

and rich-text

and red text will work.

If you want it to be a strict hierarchy, you can simply use >

, which means it has to follow the given matches directly.

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

      

ONLY applies red text color if the class inner

is inside random

inside rich-text

and it must follow this hierarchy and cannot have anything else in between

0


source


As per your example, you need to use the direct children css selector (and not deeper):

.rich-text > *

      



This means that the rules only apply to direct children of .rich-text.

0


source


Just set the rules for .inner

and all its descendants go 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>
      

Run codeHide result


0


source







All Articles