CSS :not() | Select All Elements Except Specified One

The CSS :not pseudo-class is used when we need to select and apply style to all elements except the specified one. For example, the following CSS code applies a defined style to all elements except P.

:not(p) {text-align: center;}

The above CSS code aligns all elements to the center (horizontally) of the page, except p elements or paragraphs.

CSS :not Syntax

The syntax to use the CSS :not selector to apply the style to all HTML elements except the specified one is:

:not(selector) {declarations}

CSS :not() Example

Consider the following code as an example demonstrating ":not()" in CSS:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p {color: black;}
      :not(p) {color: brown;}
   </style>
</head>
<body>

   <h2>The CSS :not Selector</h2>
   <p>This para one.</p>
   <p>This is para two.</p>
   <span>@CSS</span>
   
</body>
</html>
Output

The CSS :not Selector

This para one.

This is para two.

@CSS

In the above example, I defined two CSS rules so that HTML elements could be chosen without regard to type.

The first CSS rule uses the color property to select all p elements and change their text color to black.

Whereas the second CSS rule selects all elements that aren't p elements using the :not() pseudo-class and then uses the color property to set their text colors to brown. To match any element that isn't a p element in this case, we're using the all-encompassing selector *.

Along with the p elements, the HTML code also contains a h2 element and a span element. The first CSS rule does not apply to the h2 and span elements because they are not p elements. The second CSS rule, however, affects the h2 and span elements and changes the text color to brown.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!