The :not() CSS3 selector

The :not() CSS3 selector

Interestingly there isn’t a lot of information about the :not() CSS3 selector on the web, so I will try to cover everything what I know about this selector and I will show some practical example where it comes handy.


The :not() CSS3 selector

The :not() CSS3 selector or also known as negation selector selects every element except what is in the parenthesis. The selector can be any single element, attribute selector, class, id or pseudo-class.


This syntax will select any element other than h1, including the body and HTML tag.

:not(h1) {
//code
}

jsFiddle example: http://jsfiddle.net/mkhXW/


This syntax will select any div other than the div with the class name of .attr

div:not(.attr) {
//code
}

jsFiddle example: http://jsfiddle.net/TrLgb/


As you can see it’s very easy to understand how the negation selector works and how to use it. I think it’s really useful when we don’t know what we want to select but we know what we don’t want to select. Now let’s look at some practical examples based on this idea.


Example one:

Select every link where the attribute is not http://blog.nmsdvid.com

a:not([href="http://blog.nmsdvid.com"]) {
//code
}

jsFiddle example: http://jsfiddle.net/mYFHG/


Example two:

Select every link what are pointing out from a domain

a[href ^= 'http']:not([href *= 'blog.nmsdvid.']) {
//code
}

jsFiddle example: http://jsfiddle.net/QwhFF/


Browser Support

Since this is a CSS3 selector the browser support is poor, modern browsers like Firefox, Chrome, Safari, Opera, IE9 are supporting it but older browsers like IE7, IE8 doesn’t. But these are the situations where selectivizr comes and rescue us. By using the selectivizr JavaScript utility the :not() CSS3 selector will be cross browser .