:not() Back
:not()
is a CSS negation pseudo-class selector. It is a functional pseudo-class selector that takes a simple selector as an argument, and then matches one or more elements that are not represented by the argument.- The simple selector that
:not()
takes as an argument can be any of the following:- Type selector (eg.
span
etc.) - Class selector (eg.
.element
,.sidebar
etc.) - ID selector (eg.
#element
etc.) - Pseudo-class selector (eg.
:first-child
,last-of-type
etc.) - Attribute selector (eg.
[type="checkbox"]
etc.) - The universal selector (
*
)
- Type selector (eg.
- Invalid situation (pseudo-element and negation pseudo-class selector):
/** Invalid */
p:not(:not(.same)) {}
p:not(:not(:last-child)) {}
:not(::first-letter) {}
a:not(::after) {}
- example:
li:not(.new) {
/**
* style all the list item except the one that
has the class new
*/
}
Case: learnning :not()
See the Pen MKXxOM by aleen42 (@aleen42) on CodePen.
Note
- The
:not()
selector can be chainable with more.
artical:not(#feature):not(.header) {
/** style the artical element match the situation */
}
- The
:not()
pseudo-class selector allows useless selectors to be written. For instance:not(*)
, which represents no element at all will never apply any styles, orfoo:not(bar)
(e.gp:not(article)
), which is equivalent to foo but with a higher specificity. - Since you can use
:not()
globally and select all elements that are not represented by the argument, you should also note that:not(X)
will match anything that isn't X, including html and body. - Future levels of CSS (Level 4) will allow using selector lists inside
:not()
, such as.title:not(h1, h2)
and:not(#ID, .classname)
.