HTML and CSS Reference
In-Depth Information
a combinator. Those restrictions may (indeed most likely will) be lifted in a post-Level
3 specification, but we can still do quite a lot even within the given constraints.
For example, let's flip around the previous example and select all elements with a
class
of
moreinfo
that are not list items. This is illustrated in
Figure 1-42
.
.moreinfo:not(li) {font-style: italic;}
Figure 1-42. Styling elements with a certain class that aren't list items
Translated into English, the selector would say, “Select all elements with a
class
whose
value contains the word
moreinfo
as long as they are not
li
elements.” Similarly, the
translation of
li:not(.moreinfo)
would be “Select all
li
elements as long as they do
not have a
class
whose value contains the word
moreinfo
.”
Technically, you can put a universal selector into the parentheses, but there's very little
point. After all,
p:not(*)
would mean “Select any
p
element as long as it isn't any
element” and there's no such thing as an element that is not an element. Very similar
to that would be
p:not(p)
, which would also select nothing. It's also possible to write
things like
p:not(div)
, which will select any
p
element that is not a
div
element—in
other words, all of them. Again, there is very little reason to do so.
You can also use the negation pseudo-class at any point in a more complex selector.
Thus to select all tables that are not children of a
section
element, you would write
*:not(section) > table
. Similarly, to select table header cells that are not part of the
table header, you'd write something like
table *:not(thead) > tr > th
, with a result
like that shown in
Figure 1-43
.
What you cannot do is nest negation pseudo-classes; thus,
p:not(:not(p))
is invalid
and will be ignored. It's also, logically, the equivalent of simply writing
p
, so there's no
point anyway. Furthermore, you cannot reference pseudo-elements (which we'll cover
shortly) inside the parentheses, since they are not simple selectors.
On the other hand, it's possible to chain negations together to create a sort of “and also
not this” effect. For example, you might want to select all elements with a class of link
that are neither list items nor paragraphs.
*.link:not(li):not(p) {font-style: italic;}
That translates to “Select all elements with a
class
whose value contains the word
link
as long as they are neither
li
nor
p
elements.”