Home > Software engineering >  Apply css rule on everything but not a selector and its children
Apply css rule on everything but not a selector and its children

Time:03-24

I'm trying to achieve a scenario that a css rule should be applied to all selectors except one selector and whatever underneath it.
For example I want to apply the css on everything inside .parent but not including .child and its children.

I tried the following, but didn't work...

.parent *:not(.child *) {
  background-color: red;
}
<div >
  <div >
    <div>inside</div>
    <div>inside2</div>
  </div>
  <div>outside</div>
</div>

CodePudding user response:

You can target the child class with its own rule using "unset" or "initial" or another reasonable default value:

.parent {
  background-color: red;
}

.child {
  background-color: unset;
}

CodePudding user response:

Does this work for you?

.parent> :not(.child),
.parent> :not(.child) * {
  background-color: red;
}
<div >
  <div >
    <div>inside</div>
    <div>inside2</div>
  </div>
  <div>outside</div>
  <div>
    <div>outside!</div>
  </div>
</div>

.parent *:not(.child *)

Target any descendant of .parent that doesn't have the child class

.parent > :not(.child)

Target any direct child of .parent that doesn't have the class of child

.parent > :not(.child), .parent > :not(.child) *

Also target all descendants (the second example works as well because background-color is an inherited property)

  • Related