CSS :not 选择器

2025-06-10

CSS :not 选择器

SamanthaMing.com 的代码小贴士

无需使用两个不同的选择器来指定样式,然后再用另一个选择器来取反。使用 :not 选择器来选择除与传入参数匹配的元素之外的所有元素👍

/* ❌ */

li {
  margin-right: 10px;
}

li:first-of-type {
  margin-right: 0;
}

/* ✅ Much Better */

li:not(:first-of-type) {
  margin-right: 10px;
}
Enter fullscreen mode Exit fullscreen mode

允许的参数

在当前草案 CSS 选择器级别 3 中,您只能传递简单选择器作为参数。

简单选择器:

  • 类型选择器
  • 通用选择器
  • 属性选择器
  • 类选择器
  • ID 选择器
  • 伪类
/* Type */
h1 {}

/* Universal */
* {}

/* Attribute */
a[title] {}

/* Class */
.parent {}

/* ID */
#demo {}

/* Pseudo-class */
:first-child {}
Enter fullscreen mode Exit fullscreen mode

CSS 版本控制简述

就像 JavaScript 或 ECMAScript 有不同版本一样,CSS 也有不同版本。然而,与 ECMAScript 中所有内容都归入一个大类别(ES5、ES6、ES7)不同,CSS 是分块运行的。

例如,他们有CSS 选择器 3 级CSS 网格布局 1 级CSS 弹性框 1 级。这些:not选择器都符合CSS 选择器 3 级规范。CSS 工作组正在开发的下一个选择器是……提示一下,3 级之后是什么……叮叮,CSS 选择器 4 级😜

Rachel Andrew 写了一篇精彩的文章,解释了CSS 级别,我也在资源部分提供了链接,所以如果你感兴趣的话可以读一读🤓

传递选择器列表

在当前版本中,您只能将简单选择器作为参数传递。不过,在 CSS 选择器 4 级中,您将能够传递选择器列表。太酷了吧👏。

/* CSS Selectors Level 3 */
p:not(:first-of-type):not(.special) {}

/* CSS Selectors Level 4 */
p:not(:first-of-type, .special) {}
Enter fullscreen mode Exit fullscreen mode

以下是将要选择的内容

<div>
  <p>1</p>
  <p>2</p><!-- selected -->
  <p>3</p><!-- selected -->
  <p class="special">4</p>
  <p>5</p><!-- selected -->
</div>
Enter fullscreen mode Exit fullscreen mode

不允许嵌套否定🙈

需要指出的是,否定不能嵌套。所以这是不行的:

:not(:not(...)) {}
Enter fullscreen mode Exit fullscreen mode

:first-child对比:first-of-type

让我们首先分别定义它们:

:first-child仅当第一个元素是其父元素的第一个子元素时才选择它。这意味着,如果它不是父元素的第一个子元素,则不会选择任何元素。

:first-of-type将选择您指定类型的第一个元素。即使它不是其父元素的第一个子元素。因此,如果您使用此选择器,结果将始终显示(除非您选择了一个根本不存在的元素)。

好吧,我们来看一些例子。

孩子们都是同一类型的

因为子类型都相同,所以两者的结果也相同。

<div>
  <p></p> <!-- p:first-child, p:first-of-type -->
  <p></p>
</div>
Enter fullscreen mode Exit fullscreen mode

孩子有不同的类型

<div>
  <h1></h1>
  <p></p> <!-- p:first-of-type -->
  <p></p>
</div>
Enter fullscreen mode Exit fullscreen mode

但是因为p不再是第一个子元素。如果您调用p:first-child,则不会选择任何元素。

<!-- ⚠️ p:first-child ➡️ no element selected -->
<div>
  <h1></h1>
  <p></p>
  <p></p>
</div>
Enter fullscreen mode Exit fullscreen mode

选择第一个孩子

你可能会想,如果我不关心类型,只想选择其父级的第一个子级,该怎么办?在这种情况下,你可以这样做:

.parent :first-child {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode
<div class="parent">
  <h1></h1><!-- selected -->
  <p></p>
  <p></p>
</div>
Enter fullscreen mode Exit fullscreen mode

其他类似的 CSS 伪类

这种理解也适用于其他表亲类:

  • :last-child:last-of-type
  • :nth-child:nth-of-type
  • :only-childonly-of-type

浏览器支持

:not大多数现代浏览器和 Internet Explorer 9 及更高版本都支持该选择器。

浏览器兼容性

资源


感谢阅读❤
打个招呼!Instagram | Twitter | Facebook | Medium |博客

鏂囩珷鏉ユ簮锛�https://dev.to/samanthaming/css-not-selector-ek2
PREV
点符号 vs 括号符号
NEXT
使用 Spread 将 Iterable 转换为数组 使用 Spread 将 Iterable 转换为数组