Sunil Sunil - 5 months ago 25
CSS Question

Use :not selector to exclude a div and all its descendants

I have a situation where a style of purple font color with a light yellow background needs to be applied to all divs outside a div having a class of

RadDiv
.

This means all divs that are nested within the div with class of
RadDiv
should be excluded.

I tried using
:not
selector as shown below but it does not work. Demo of my situation

Question: How would I specify the
:not
selector to exclude a div with a class of
RadDiv
and all nested divs inside this div?

:not selector that does not work

div:not(.RadDiv) div {
background-color:lightyellow;
color:purple;
}


Complete code that I tried

<div>This is a div </div>
<div class="RadDiv newDiv outerDiv">
<div class="header">
This is the header
</div>

This is an outer div

<div class="alert highlight">
This div stands out
</div>
<div class="footer disclaimer">
This is the footer part
</div>
<table>
<tr>
<td>
<div>This is div inside a table element</div>
</td>
</tr>
</table>
</div>
<div id="div1">This is div1</div>
<div id="div2">This is div2</div>
<style>
div:not(.RadDiv) div {
background-color:lightyellow;
color:purple;
}
.outerDiv {
border:1px solid red;
font-family:Arial;
}
.footer {
color:lightgray;
font-size:small;
font-style:italic;
}
.header {
font-weight:bold;
}

Answer

Treat all divs of the same level as siblings. Therefore, start by selecting the parent:

body > div:not(.RadDiv) {
    background-color: lightyellow;
    color: purple;
}

Using the child combinator (>), only one level is targeted, and the :not selector can be used to exclude any sibling.

Revised Fiddle

References: