css伪类nth-child和nth-of-type的区别
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
#aa .aa:nth-child(1){border:1px solid red}
#bb .bb:nth-of-type(1){border:1px solid blue}
</style>
</head>
<body>
<p>nth-child:</p>
<div id="aa">
<div class="aa">div</div>
<span class="aa">span</span>
<p class="aa">p</p>
<h1 class="aa">h1</h1>
<h2 class="aa">h2</h2>
</div>
<p>nth-of-type:</p>
<div id="bb">
<div class="bb">div</div>
<span class="bb">span</span>
<p class="bb">p</p>
<h1 class="bb">h1</h1>
<h2 class="bb">h2</h2>
</div>
</body>
</html>
页面效果:

同样是设置第一个元素样式:
nth-child只考虑父元素下的子元素个数,不考虑元素类型;
nth-of-type考虑的是父元素下存在的元素类型,并把每种类型单独统计计数。
本文深入解析了CSS中nth-child和nth-of-type两个伪类的选择器功能。通过实例演示,对比了两者在处理元素选择时的不同之处。nth-child依据子元素的位置进行选择,而nth-of-type则针对特定类型的子元素进行计数。
2912

被折叠的 条评论
为什么被折叠?



