How to Use the :not CSS pseudo-class with Examples

The :not CSS pseudo-class allows you to apply styles to elements that do not match a specific selector. This can be useful when you want to exclude certain elements from a selector or apply a different style to them. In this blog post, we’ll show you how to use the :not CSS rule with examples.

Syntax

The :not CSS pseudo-class is used to select elements that do not match a specific selector. The syntax is as follows:

:not(selector) {
  /* styles */
}

In this syntax, selector is the selector that you want to exclude. The :not pseudo-class is followed by parentheses that contain the selector argument. Inside the braces, you can define the styles that you want to apply to elements that do not match the selector.

Example 1: Select All Paragraphs Except the First One

Let’s say you have a webpage with several paragraphs and you want to apply a different style to all paragraphs except the first one. You can use the :not(:first-of-type) selector to exclude the first paragraph. Here’s an example:

<p>First paragraph.</p>
<p>Second paragraph.</p>
<p>Third paragraph.</p>
p:not(:first-of-type) {
  color: red;
}

In this example, we’re using the p:not(:first-of-type) selector to select all paragraphs except the first one and apply a red color to them. This will make the second and third paragraphs appear red, but not the first one.

Example 2: Select All Links Except Those with a Specific Class

Let’s say you have a webpage with several links and you want to apply a different style to all links except those with a specific class. You can use the :not(.classname) selector to exclude links with the classname class. Here’s an example:

<a href="#">Link 1</a>
<a href="#" class="exclude">Link 2</a>
<a href="#">Link 3</a>
a:not(.exclude) {
  text-decoration: underline;
}

In this example, we’re using the a:not(.exclude) selector to select all links except those with the exclude class and apply an underline style to them. This will make the first and third links appear underlined, but not the second one.

Example 3: Select All Elements Except Those Inside a Specific Element

Let’s say you have a webpage with several elements and you want to apply a different style to all elements except those inside a specific element. You can use the :not(selector) selector to exclude elements inside a specific selector. Here’s an example:

<div>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</div>
<p>Paragraph 3</p>
:not(div) p {
  color: blue;
}

In this example, we’re using the :not(div) p selector to select all paragraphs except those inside a div element and apply a blue color to them. This will make the third paragraph appear blue, but not the first and second paragraphs.

Conclusion

The :not CSS pseudo-class is a powerful tool that allows you to select elements that do not match a specific selector. By using the :not rule, you can exclude certain elements from a selector or apply a different style to them. By following