CSS :not()伪类选择器是一个反向选择器,它用于匹配不是:not()参数指定的某类元素。
:not()可以接收的参数包括以下的类型:
- 类型选择器
- class类选择器
- id选择器
- 伪类选择器
- 属性选择器
- 通用选择器(
*)
:not()的参数不能是一个伪元素,如::before和::after,也不能是另外一个:not()伪类选择器。例如下面的CSS规则是错误的:
/* 错误的CSS规则 */
p:not(:not(.same)) {}
p:not(:not(:last-child)) {}
:not(::first-letter) {}
a:not(::after) {}
:not()不能够嵌套:not(),也不能够嵌套在:matches()伪类选择器中(:matches(:not(..)))。
正如上面提到的,:not()匹配非参数指定的元素,例如下面的代码匹配所有非.foo的元素:
li:not(.foo) {
/* 为所有非带.foo class的列表项元素设置样式 */
}
可以串联多个:not()选择器,例如下面的CSS规则先匹配所有不带ID为featured的article元素,然后在从中过滤出所有带class tutorial的元素。
article:not(#featured):not(.tutorial) {
}
:not()选择器也可以不应用在一个元素上,而是作为“全局”选择器。此时它会选择器文档中所有非参数指定的元素。例如:
:not(a) {
color: #333;
}
示例代码
下面有效的:not()声明代码:
:not(a) {
}
p:not(:first-of-type) {
}
a:not([href = "http://www.google.com"]) {
}
input[type="text"]:not([disabled="disabled"]) {
}
h1:not(#page-title) {
}
浏览器支持
所有的现代浏览器都支持:not伪类选择器,包括:Chrome, Firefox, Safari, Opera9.5+, Internet Explorer 9+ 以及 Android 和 iOS。