在开发的时候,nth-of-type和nth-child是比较常用的伪类。
这两个的作用原理是这样的:
nth-of-type: 序号的计算是这样的,父类下,与本元素相同的元素,都会计算进总数里。
nth-child: 序号的计算是这样的,父类下,所有的直接子元素,都会计算进总数里
html里的结构如下:
<div>
<h1>test h1</h1>
<div>test div</div>
<h1 class="type"> type test</h1>
<h1 class="type"> type test</h1>
</div>
我们想要将第一个.type元素的背景设为红色,第二个.type 设为蓝色,我们容易这样写
.type:nth-of-type(1){
background:red
}
// 实际生效元素为 <h1>test h1</h1>
.type:nth-child(2){
background:blue
}
// 实际生效元素为 <div>test div</div>
这种写法,是错误的。无法实现我们想要的结果。
有效的做法,应该是加不同的类名做区分