CSS has some selectors that allow you to select elements in certain conditions such as :hover, :focus, :active, etc. Yet today we will not cover those selectors. We will look into one which is still a little known method but used by most web designers – that is the :not selector or also known as negation selector.

What does it do?

I’m sure that the :not name itself has already described its function, that it will simply select the opposite of the element or condition specified. For example:

This syntax will select any element other than p (paragraph).

:not(p)

While the example syntax below will select the div element that does not have class abc

div:not(.abc)

All right, now, let’s try this selector in a real example:

First of all, let’s make a few paragraphs with a few links from Wikipedia and a few links with fictional domains. Here is the HTML markup for the paragraph.

The plan here is: we will select only the links that is not pointing to Wikipedia and then give those links an exclamation mark to alert attention towards those links.

First, we will add an :after pseudo-element on all the links to place the mark, and we define it as an inline-block element.

a:after {
display: inline-block;
}

Then, to select every link that is not pointing to Wikipedia, we will combine the :not selector with an attribute selector. The attribute selector here will select every anchor tag which the href attribute begins with http://en.wikipedia.org/ and by combining it with the :not, it will obviously select the opposite. So here we go:

Conclusion

In some circumstances using the :not selector is really the most effective option, just like the above example, where we are able to select some random elements without even adding unnecessary class, or additional markup to the document.