Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
Hunter Turner Avatar asked Feb 19 '16 15:02

Hunter Turner


People also ask

What does not () do in CSS?

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.

Can I use CSS not selector?

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.

What CSS selector should we use if we want to select all elements but not the specified class or selector?

For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class.

How do I apply CSS to child element based on parent?

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.


2 Answers

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.

like image 39
Brian FitzGerald Avatar answered Oct 23 '22 10:10

Brian FitzGerald


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>
like image 193
Shomz Avatar answered Oct 23 '22 10:10

Shomz