:not() | CSS属性参考

1,030次阅读
没有评论

共计 927 个字符,预计需要花费 3 分钟才能阅读完成。

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。

相关阅读
正文完
 0