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

问题描述

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

两者有什么区别?

解决方法

来自the specification

:nth-of-type(1):first-of-type 伪类表示作为其类型的第一个兄弟元素的元素。

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

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

例如:

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

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