I would like to write a CSS selector rule that selects all elements that don\'t have a certain class. For example, given the following HTML:
I think this should work:
:not(.printable)
From "negative css selector" answer.
:not([class])
Actually, this will select anything that does not have a css class (class="css-selector"
) applied to it.
I made a jsfiddle demo
h2 {color:#fff}
:not([class]) {color:red;background-color:blue}
.fake-class {color:green}
<h2 class="fake-class">fake-class will be green</h2>
<h2 class="">empty class SHOULD be white</h2>
<h2>no class should be red</h2>
<h2 class="fake-clas2s">fake-class2 SHOULD be white</h2>
<h2 class="">empty class2 SHOULD be white</h2>
<h2>no class2 SHOULD be red</h2>
Is this supported? Yes : Caniuse.com (accessed 02 Jan 2020):
Funny edit, I was Googling for the opposite of :not. CSS negation?
selector[class] /* the oposite of :not[]*/
The negation CSS pseudo-class,
:not(X)
, is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector.
You can use :not
to exclude any subset of matched elements, ordered as you would normal CSS selectors.
div:not(.class)
Would select all div
elements without the class .class
div:not(.class) {
color: red;
}
<div>Make me red!</div>
<div class="class">...but not me...</div>
:not(div) > div
Would select all div
elements which arent children of another div
div {
color: black
}
:not(div) > div {
color: red;
}
<div>Make me red!</div>
<div>
<div>...but not me...</div>
</div>
With the notable exception of not being able to chain/nest :not
selectors and pseudo elements, you can use in conjunction with other pseudo selectors.
div {
color: black
}
:not(:nth-child(2)){
color: red;
}
<div>
<div>Make me red!</div>
<div>...but not me...</div>
</div>
:not
is a CSS3 level selector, the main exception in terms of support is that it is IE9+
The spec also makes an interesting point:
the
:not()
pseudo allows useless selectors to be written. For instance:not(*|*)
, which represents no element at all, orfoo:not(bar)
, which is equivalent tofoo
but with a higher specificity.
Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,
input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}
Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.