第 n 个类型的伪选择器在这里按预期工作。
来自 MDN:
:nth-of-type(an+b) CSS 伪类匹配在文档树中它之前有 an+b-1 个相同元素名称的兄弟元素的元素
因此
.test3:nth-of-type(3) {height: 100px;background: black;}
"
'works'是因为具有class为test3的div恰好也是容器(class为test的div)中的第三个div。
然而,
"
.test3:nth-of-type(1) {height: 100px;background: black;}
由于它不是容器中的第一个div,因此不选择test3 div。
在这种情况下,nth-of-type
和nth-child
的工作方式相同吗?
在这种情况下,它们是相同的,因为容器中的所有子元素都是div。
一般来说,我们可以将伪类看作是一个
过滤器,它只匹配选择器的子集(即冒号前面的部分),当它处于伪类所描述的
状态时。
例如,
.test:hover
表示:选择所有具有 class 为 test 的元素 - 但只选择正在被悬停的元素。
同样地,在这里 nth-of-type:
.test3:nth-of-type(3)
表示:
选择所有具有 class 为 test3 的元素,但仅当它是其容器中该类型元素的第三个时。
因此,请看以下演示:
.test:nth-of-type(3) {
color:red;
}
<div>
<ul>
<li class="test">li 1</li>
<li class="test">li 2</li>
<li class="test">li 3</li>
<li class="test">li 4</li>
<li class="test">li 5</li>
</ul>
<span class="test">span 1</span>
<span class="test">span 2</span>
<span class="test">span 3</span>
<span class="test">span 4</span>
<span class="test">span 5</span>
</div>
请注意,第三个列表项和第三个span都被样式化了 - 这是因为它们都有test类,并且是容器中该类型元素的第三个
NB:
当使用未限制类型选择器的nth-of-type
伪类时 - 所有类型都会匹配 - 就像使用通用选择器一样。
例如:
.test:nth-of-type(3)
等同于 *.test:nth-of-type(3)
演示:
.test:nth-of-type(3) {
color:red;
}
<div>
<fred class="test">fred 1</fred>
<div class="test">div 1</div>
<span class="test">span 1</span>
<p class="test">p 1</p>
<p class="test">p 2</p>
<p class="test">p 3</p>
<p class="test">p 4</p>
<span class="test">span 2</span>
<fred class="test">fred 2</fred>
<fred class="test">fred 3</fred>
<span class="test">span 3</span>
</div>
test3
,为什么要使用nth-of-type
? - Carl Binalla