CSS :not 选择器
无需使用两个不同的选择器来指定样式,然后再用另一个选择器来取反。使用 :not 选择器来选择除与传入参数匹配的元素之外的所有元素👍
/* ❌ */
li {
margin-right: 10px;
}
li:first-of-type {
margin-right: 0;
}
/* ✅ Much Better */
li:not(:first-of-type) {
margin-right: 10px;
}
允许的参数
在当前草案 CSS 选择器级别 3 中,您只能传递简单选择器作为参数。
简单选择器:
- 类型选择器
- 通用选择器
- 属性选择器
- 类选择器
- ID 选择器
- 伪类
/* Type */
h1 {}
/* Universal */
* {}
/* Attribute */
a[title] {}
/* Class */
.parent {}
/* ID */
#demo {}
/* Pseudo-class */
:first-child {}
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) {}
以下是将要选择的内容
<div>
<p>1</p>
<p>2</p><!-- selected -->
<p>3</p><!-- selected -->
<p class="special">4</p>
<p>5</p><!-- selected -->
</div>
不允许嵌套否定🙈
需要指出的是,否定不能嵌套。所以这是不行的:
:not(:not(...)) {}
:first-child
对比:first-of-type
让我们首先分别定义它们:
:first-child
仅当第一个元素是其父元素的第一个子元素时才选择它。这意味着,如果它不是父元素的第一个子元素,则不会选择任何元素。
:first-of-type
将选择您指定类型的第一个元素。即使它不是其父元素的第一个子元素。因此,如果您使用此选择器,结果将始终显示(除非您选择了一个根本不存在的元素)。
好吧,我们来看一些例子。
孩子们都是同一类型的
因为子类型都相同,所以两者的结果也相同。
<div>
<p></p> <!-- p:first-child, p:first-of-type -->
<p></p>
</div>
孩子有不同的类型
<div>
<h1></h1>
<p></p> <!-- p:first-of-type -->
<p></p>
</div>
但是因为p
不再是第一个子元素。如果您调用p:first-child
,则不会选择任何元素。
<!-- ⚠️ p:first-child ➡️ no element selected -->
<div>
<h1></h1>
<p></p>
<p></p>
</div>
选择第一个孩子
你可能会想,如果我不关心类型,只想选择其父级的第一个子级,该怎么办?在这种情况下,你可以这样做:
.parent :first-child {
color: blue;
}
<div class="parent">
<h1></h1><!-- selected -->
<p></p>
<p></p>
</div>
其他类似的 CSS 伪类
这种理解也适用于其他表亲类:
:last-child
和:last-of-type
:nth-child
和:nth-of-type
:only-child
和only-of-type
浏览器支持
:not
大多数现代浏览器和 Internet Explorer 9 及更高版本都支持该选择器。
资源
- MDN Web 文档 - CSS :not
- w3schools - CSS :not
- W3C - CSS :not
- CSS 技巧 - CSS :not
- caniuse - CSS :not
- 为什么没有 CSS4 - 解释 CSS 级别
- w3schools - CSS :first-child
- w3schools - CSS :first-of-type
感谢阅读❤
打个招呼!Instagram | Twitter | Facebook | Medium |博客