先从最不容易理解的only-child,only-of-type说起吧,理解这两个后面的都好理解了。
1. only-child
选取条件:需要有父元素(不包含body元素),父元素下只有一个元素,且该唯一个元素为指定元素。
a:only-child{
color:blue;
}
<body>
<div>
<div>
<a>a标签1</a>
</div>
</div>
<div>
<div>
<a>a标签2</a> // 不满足“父元素下只有一个元素”条件
<p>p标签</p>
</div>
</div>
<div>
<div>
<a>a标签3</a> // 不满足“唯一个元素为指定元素”条件
<a>a标签4</a> // 同上
</div>
</div>
<a>a标签5</a> // 不满足“有父元素(不包含body元素)”条件
</body>
2. only-of-type
选取条件:有父元素(包含body元素),指定元素在父元素中唯一。
a:only-of-type{
color:blue;
}
<body>
<div>
<div>
<a>a标签1</a>
</div>
</div>
<div>
<div>
<a>a标签2</a>
<p>p标签</p>
</div>
</div>
<div>
<div>
<a>a标签3</a> // 不满足"指定元素在父元素中唯一"条件
<a>a标签4</a> // 同上
</div>
</div>
<a>a标签5</a>
</body>
3. nth-child
选取条件:选取在每一个具有子元素的元素(包含body元素)中,指定位置为指定元素的元素。注意:指定位置是指第几个child,无论是什么元素。
a:nth-child(2){
color:blue;
}
<body>
<div>
<div>
<a>a标签1</a> // 不是指定位置2,是该div的第1个child
<a>a标签2</a>
</div>
<div>
<a>a标签3</a> // 不是指定位置2,是该div的第1个child
<p>p标签</p> // 不是指定元素a
</div>
</div>
<a>a标签4</a>
<a>a标签5</a> // 不是指定位置2,是body的第3个child
</body>

和nth-child()相似,只不过指定位置是和nth-child()相反,也就是从后往前计数。
last-of-type
相当于nth-last-of-type(1).
first-child
相当于nth-child(1).
4. nth-of-type
选取条件:选取在每一个具有子元素的元素(包含body元素)中,指定位置为指定元素的元素。注意:指定位置是指第几个指定元素。
a:nth-of-type(2){
color:blue;
}
<body>
<div>
<div>
<a>a标签1</a> // 不是指定位置2,是该div的第1个a
<a>a标签2</a>
</div>
<div>
<p>p标签</p>
<a>a标签3</a> // 不是指定位置2,是该div的第1个a
</div>
</div>
<a>a标签4</a> // 不是指定位置2,是body的第1个a
<a>a标签5</a>
</body>
nth-last-of-type()
和nth-of-type()相似,只不过指定位置是和nth-of-type()相反,也就是从后往前计数。
last-of-type
相当于nth-last-of-type(1).
first-of-type
相当于nth-of-type(1).