Exclude Any Class Name in CSS With This Selector

Ferenc Almasi • 2022 September 12 • 📖 2 min read

To exclude a class in CSS, we can use the :not pseudo-class selector, also known as the not selector.

:not(.class) {
    background: red;
Copied to clipboard!

This can be used to style any element that is not matched by the selector written in parentheses. It accepts any valid CSS selector, and can also be chained off from other elements. For example:

/* Select all p tags that doesn't have the class "highlighted" */
p:not(.highlighted) {

/* Select every p, but not the last */
p:not(:last-child) {
    background: red;
Copied to clipboard!

First paragraph

Second paragraph

Last paragraph with a :not(:last-child) selector

As you can see, the selector can be used with other than class selectors. There are also a couple of rare cases you should keep in mind whenever you use the :not selector. These are the following:

/* Using the :not selector with a wildcard selector */

/* Globally using the :not selector */

/* Using :not with an invalid selector */
Copied to clipboard!
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
🎉 Thank you for subscribing to our newsletter. x