nth-child和nth-of-type的区别
选择器:nth-child
选择器:nth-of-type
都是找该选择器父元素的子元素;
案例
</head>
<style>
.nth:nth-child(3){
background-color: red;
}
.nth:nth-of-type(3){
background-color: green;
}
</style>
</head>
<body>
<div class="nth">1</div>
<div class="nth">2</div>
<p class="nth">3</p>
<p class="nth">4</p>
<div class="nth">5</div>
<p class="nth">6</p>
</body>
.nth:nth-child(3)
1.找到.nth
元素父元素下所有的子元素,这里body是父元素;
2.找到第3个元素, 再对该元素匹配类选择器.nth
, 匹配成功则添加样式;
.nth:nth-of-type(3)
1.找到.nth
元素父元素下所有的子元素,这里body是父元素;
2.找到其中满足类选择器.nth
的元素,并归类得到两种标签名:div
,p
(这就是nth-of-type中type的含义);
3.对body下所有的元素按以上的标签名分组;
#第一组
<div class="nth">1</div>
<div class="nth">2</div>
<div class="nth">5</div>
#第二组
<p class="nth">3</p>
<p class="nth">4</p>
<p class="nth">6</p>
4.然后分别找到每组内第3个元素,分别对找到的第3个元素匹配类选择器.nth
;
1
1
1
1
1
1
1
1
1
1