nth-of-type(1) 和 first-of-type 伪 类 之间的区别

Difference between nth-of-type(1) and first-of-type pseudo-classes

我很好奇第 nth-of-type(1) 和 first-of-type 之间有什么区别。从我的用法来看,它们似乎做同样的事情,但是每个代码示例都将使用第一个类型而不是第一个类型 (1),如果它是第一个元素。

两者有什么区别?

来自the specification

Same as :nth-of-type(1). The :first-of-type pseudo-class represents an element that is the first sibling of its type.

它们是相同的,我们都同意这一点,但我们可能需要它们用于不同的用例。

想象一下我需要编写一个 SASS 循环来创建基于索引的选择器的情况。我将使用 :nth-of-type

例如:

@for $i from 1 through $n {
 .container > div:nth-of-type(#{$i}) { ... }
}

有时我只需要定位第一个元素,这样我就可以简单地使用 first-of-type 这将使代码更易于阅读。