Skip to main content

{clairecodes}

The :not() pseudo-class

  1 minute read
  Categories: 

How do you use CSS to style a particular element differently from other similar elements? You’d stick a class or ID on it, like so:

<style>
.special {
    color: red;
}
</style>

<p>Normal</p>
<p>Normal</p>
<p class="special">Special</p>
<p>Normal</p>
<p>Normal</p>

Normal

Normal

Special

Normal

Normal


But what if you have the opposite problem - you want to exclude an element from a particular style?

Maybe you’d try and override your styling with another class, but why not use the handy :not() CSS pseudo-class instead:

<style>
p:not(.special) {
    color: red;
}
</style>

<p>Normal</p>
<p>Normal</p>
<p class="special">Special</p>
<p>Normal</p>
<p>Normal</p>

Normal

Normal

Special

Normal

Normal


In one selector you can apply a style to all the elements except for ones that match the selector within the :not().

A pseudo-class is a keyword that you add to CSS selector that makes it more specific to the state of the element: other pseudo-classes are :hover and :focus.

Try using this when you’re thinking of styling a table with a :last-child selector.

Moar