[CSS] How to select elements that do not belong to a specific parent

Created on 22 Nov 2023

Imagine that you have following HTML structure:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<a>
    <b>
        <c></c>
    </b>
    <c></c>
    <d>
        <c></c>
    </d>
    <e>
        <c></c>
    </e>
</a>

Now we want to set some styles on all <c> elements except the one which is inside <d> element. For the sake of this example we will make let elements have a red background.

Solution to this problem is very easy. We can use :not() and give him a path to the element that we want to ommit.

1
2
3
c:not(d c) {
    background: red;
}

As a result our structure will have 3 <c> elements painted red:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<a>
    <b>
        <c></c> <!-- will have red background -->
    </b>
    <c></c> <!-- will have red background -->
    <d>
        <c></c>
    </d>
    <e>
        <c></c> <!-- will have red background -->
    </e>
</a>

If you want to have more than one selector, you can cascade :not(). Let’s say we want to skip <c> elements in both <d> and <e> elements. To achieve that we can do following:

1
2
3
c:not(d c):not(e c) {
    background: red;
}

Now we will have only 2 <c> elements painted red:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<a>
    <b>
        <c></c> <!-- will have red background -->
    </b>
    <c></c> <!-- will have red background -->
    <d>
        <c></c>
    </d>
    <e>
        <c></c>
    </e>
</a>