:nth-child和:nth-of-type的主要区别是-type是选中后代中出现的所有类型的元素中的第一个,而-child是选中第一个出现的元素有点拗口,可能会听不懂,放个例子(如果是元素选择器的-child,比如div:first-child,则选中的是第一个div,如果第一个不是div则啥也没选中,-type同理):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#wrap .a:nth-of-type(1){
color: red;
font-size: 20px;
}
</style>
<body>
<div id="wrap">
<p class="a">我会有变化吗</p>
<div class="a">我会有变化吗</div>
<span class="a">我会变化吗</span>
<div class="a">我呢</div>
</div>
</body>
</html>
渲染出来的页面:

#wrap .a:nth-child(1){ //当我们把-type换成-child时
color: red;
font-size: 20px;
}
渲染出来的页面:

本文详细介绍了CSS选择器:nth-child和:nth-of-type的区别。通过实例演示,解释了它们在选取元素时的不同之处。 nth-child依据元素在父元素中的位置选取,而nth-of-type则根据元素类型来选取。示例代码展示了当使用这两个选择器时,不同元素颜色和字体大小的变化情况,帮助读者理解其工作原理。

1万+

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



