Exclude Any Class Name in CSS With This Selector
To exclude a class in CSS, we can use the :not
pseudo-class selector, also known as the not selector.
Copied to clipboard!
:not(.class) {
background: red;
}
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:
Copied to clipboard! Playground
/* 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;
}
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:
Copied to clipboard! Playground
/* Using the :not selector with a wildcard selector */
:not(*)
/* Globally using the :not selector */
:not(.class)
/* Using :not with an invalid selector */
:not(:unsupported-pseudo-class)
- In the first example, we used
:not
with the * wildcard selector. This is a useless selector that will not be applied to anything, since the selector reads: "select any element that is not an element". - When you globally use the
:not
selector (not attached to any element), it will also includehtml
andbody
. More importantly, it will also increase specificity, so#id:not(.class)
will be stronger than#id
. - Lastly, if you use an unsupported or invalid selector with
:not
, the entire rule will be invalidated, meaning no styles will be applied to the element.
π More Webtips
Master the Art of Frontend
Access exclusive interactive lessons
Unlimited access to hundreds of tutorials
Remove ads to learn without distractions
Courses

CSS - The Complete Guide (including Flexbox, Grid and Sass)
Including Flexbox, Grid, and Sass
Whether you're learning CSS for the first time or brushing up on your CSS skills and diving even deeper, this course is for you. Every web developer has to know CSS.

The HTML & CSS Bootcamp
From Zero to Expert!
This course covers flexbox, CSS grid, animations, responsive design, and much more! You will find tons of exercises & projects inside this course.

The Creative HTML5 & CSS3 Course
Build Awesome Websites
Learn HTML5 and CSS3 by creating three amazing, well-designed and animated websites from scratch.