How to Use The :not Selector in CSS

The :not() selector in CSS is a pseudo-class that lets you select and style elements that do not match a specific condition.

This selector can be very useful when you want to apply specific styles to elements that do not have a certain attribute, such as a particular class or id.

Here's the basic syntax of the :not() selector:

selector:not(condition) {
    /* Styles */
  • selector is the type of HTML element you're targeting. This is optional; you can drop the element if you only care about the condition.
  • condition is what you want to exclude in your selection.

As an example, you can target all p elements that do not have the class .highlight:

p:not(.highlight) {
    color: grey;

With this style rule, all p elements without the class .highlight will have red text.

Selecting All Elements That Don't Have a Specific Class

If you want to apply a style to all elements on the page that don't have a certain class, you can use the * (universal selector) as your selector:

*:not(.highlight) {
    background-color: grey;

/* It works even without the * explicitly set, I just prefer the verboseness */

:not(.highlight) {
    background-color: grey;

Combining Conditions

The :not() selector can also accept more than one condition, allowing you to exclude elements that match multiple attributes. This can be done by adding all conditions comma separated. For example:

/* In this example, all div elements that do not have the class .highlight or .underlined will have an orange background. */
div:not(.highlight, .underlined) {
    background-color: orange;

Beyond Classes and IDs

The :not() selector isn't just for class and id attributes—you can use it with any attribute selector. Let's quickly look at an example so you can start thinking of other ways to leverage the :not() selector.

/* This rule will apply a pink background to all input elements not of type "text". */
input:not([type="text"]) {
    background-color: pink;

Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.