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?
The :not() CSS pseudo-class represents elements that do not match a list of selectors. Since it prevents specific items from being selected, it is known as the negation pseudo-class.
The :not() property in CSS is a negation pseudo class and accepts a simple selector or a selector list as an argument. It matches an element that is not represented by the argument. The passed argument may not contain additional selectors or any pseudo-element selectors.
For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class.
It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinator ( > ), which is placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With