Home > front end >  Apply CSS selector for child element not having parent
Apply CSS selector for child element not having parent

Time:09-25

I know there is a not operator in CSS that can be used at the root level. But can I apply CSS selector for child element not having a specific parent element ?

So I have a DOM structure as below;

<div>
<button value="applyCSSToThisBtn"/>
</div>
<div id="someId" class="someClass">
<button value="DONOTapplyCSSToThisBtn"/>
</div>

So basically I want to appy some CSS to the button (but only for that which does not have id="someId" as it's parent...Also button is not necessarily direct child)

CodePudding user response:

div:not([id]) button {
  color: red;
}

How about this? Applies style to all buttons that are children of a div without an id property.

CodePudding user response:

You could use :not to point to your button that doesn't have an specified property

button{} //returns all buttons

button:not([id] {} //returns all buttons without id

CodePudding user response:

Css has a pseudo class not.

To select all those buttons which are children (or grandchildren etc) of a div where that div does not have id someId you can do this:

div:not([id="someId"]) button {
  background: magenta;
}
<div>
  <button value="applyCSSToThisBtn">should be magenta</button>
</div>
<div id="someId" class="someClass">
  <button value="DONOTapplyCSSToThisBtn">should not be magenta</button>
</div>

Note: button is not self closing so this has been corrected in this snippet.

CodePudding user response:

This selects all descendants of a parent that don't have the specified id. Run the code to see the result

div:not(#someId) button{background-color: yellow}
<div>
<button>Child1</button>
<section><button>Grandchild</button></section>
</div>

<div id="someId" class="someClass">
<button>Child2</button>
</div>

  •  Tags:  
  • css
  • Related