The CSS3 :not() selector
There isn’t a lot of information to be found about the :not()
selector. The specifications only offer 3 lines of text and a couple of examples. So lets see what it can do!
The Specification
The negation pseudo-class, :not(X), is a functional notation taking a simple selector […] as an argument. It represents an element that is not represented by the argument.
What it says here, is that a selector with a :not()
in it will match all elements that do not match what’s between the parenthesis.
A simple selector is a term used in the specifications. A simple selector is: a single element, attribute selector, class, id or pseude-class.
Examples of simple selectors:
body
*
[value="foo"]
.foo
#foo
:hover
Basically, any of the above type, but with only one selector.
The browsers
The :not()
selector is only supported by modern browsers (Firefox, Safari and Opera), :not(IE)
.
Let’s take a look at what browsers allow you to do:
div:not(.home) {…}
This selects all div elements that do not have the class .home
div *:not(p) em {…}
This selects all em elements that are in an element (that is not a p element) and that are in a div element. so <div><strong><em>…</em></strong></div>
is a match, but <div><p><em>…</em></p></div>
is not.
input:not([type="file"]) {…}
This uses the attribute selector to select all input element, save for the file upload ones.
Do you want a better understanding of your own CSS selectors? Then check out the CSS specificity calculator that explains your selectors.
You can use the :not()
selector as a part of a large selector. I’ve done this a few times in my current design:
li:not(.pingback) .comment-content p:first-child:first-line {…}
body:not(.home) h2 + p:first-letter {…}
.post:not(.first-post) a:hover {…}
The :not()
selector is a nice addition to the CSS Tookit, and it can already be used in a way that allows for graceful degradation, such as I do on this website. If you have any nice experiences with :not()
, please share them in the comments!
Hi, I'm Kilian. I make Polypane, the
browser for responsive web development and design. If you're reading this site, that's probably
interesting to you. Try it out!
Related articles
CSS & HTML , 6 October 2020There are many different ways to achieve the same layout in CSS and HTML. Some are now frowned upon, like tables or floats, and others tend to overlap somewhat, but have a clear specific purpose, like Flexbox and Grid. But CSS has another layout engine, and it’s one that has been part of CSS since…
CSS & HTML , 4 January 2021Every now and then a web developer using a Mac discovers that their beautiful design is littered with scroll bars on other platforms. Either because someone points it out to them or because they attach a mouse to their laptop, both of which make the scroll bars appear. Often, MacOS hiding scroll bars by default is…
CSS & HTML , 9 February 2016 This spec allows you to define your own selector as an alias for a list of other selectors …