以前对 CSS3 选择器理解的不准确。比如 :first-child 伪类。如果有这么一个代码片段:
1 2 3 4 5 | <div> <h1></h1> <h2></h2> <h2></h2> </div> |
给出一个组合选择器
1 | div h2:first-child{} |
能不能匹配到第一个 h2 呢?
答案是不能。因为 h2 不是 div 元素的第一个子元素。这个伪类选择器只适用于 h2 是第一个子元素的情况,如果 h2 不是第一个子元素,它什么都匹配不到。W3C 官网是这么介绍的:
The :first-child pseudo-class represents an element that is the first child of some other element.
并且明确的给出了两个例子:
This selector can represent the p inside the div of the following fragment:
1 2 3 4 <p> The last P before the note.</p> <div class="note"> <p> The first P inside the note.</p> </div>but cannot represent the second p in the following fragment:
1 2 3 4 5 <p> The last P before the note.</p> <div class="note"> <h2> Note </h2> <p> The first P inside the note.</p> </div>
那么,如果想实现匹配不是第一子元素的一组 h2 中的第一个,应该用那个选择器呢?
要用 :first-of-type 伪类。
W3C 官网给出的介绍:
The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.
因为
:first-child 和 :last-child 是 :nth-child() 的特例。
:first-of-type 和 :last-of-type 是 :nth-of-type() 的特例。
所以这几个伪类的用法是一样的。