Hunter Turner
Hunter Turner

Reputation: 6894

CSS :not() selector. Apply style if parent does not exist

I am trying to apply a style to a div based on its parent class. I am using the :not() selector to select the div whose parent is not .container1, the second div should be red, but it's not working.

Example 1

.myDiv:not(.container1) > .myDiv {
  color: red;
}
<div class="container1">
  <div class="myDiv">Div 1</div>
</div>

<div class="container2">
  <div class="myDiv">Div 2</div>
</div>

Example 2

.myDiv:not(.container1 .myDiv) {
  color: red;
}
<div class="container1">
  <div class="myDiv">Div 1</div>
</div>

<div class="container2">
  <div class="myDiv">Div 2</div>
</div>

Is this even possible with CSS? Or is my syntax just off?

Upvotes: 14

Views: 37357

Answers (2)

Brian FitzGerald
Brian FitzGerald

Reputation: 3109

CSS can't do "parent lookups" like that. You would need to reverse the structure to something like:

.my-container:not(.container1) .myDiv

Granted, you would need to add the shared my-container class to all "parent" divs of interest.

Upvotes: 5

Shomz
Shomz

Reputation: 37701

You're selecting wrong elements. No reverse lookups possible, see here:

div:not(.container1) > .myDiv {
  color: red;
}
<div class="container1">
  <div class="myDiv">Div 1</div>
</div>

<div class="container2">
  <div class="myDiv">Div 2</div>
</div>


Ideally, you'd group those parent divs under the same class in order to avoid the super-generic div selector:

.container:not(.container1) > .myDiv {
  color: red;
}
<div class="container container1">
  <div class="myDiv">Div 1</div>
</div>

<div class="container container2">
  <div class="myDiv">Div 2</div>
</div>

Upvotes: 20

Related Questions