nth-child,nth-of-type,first-of-type,last-of-type,nth-last-of-type,only-of-type等的区别

类型

*-child和*-of-type分别有五个前缀,即:nth,nth-last,first,last,only。


其中nth和nth-last需要传入参数,即第n元素的n值


first前缀等同于nth前缀传入参数1,last前缀等同于nth-last传入参数1。


即first-child和nth-child(1)等同,first-of-type和nth-of-type(1)等同,last-child和nth-last-child(1)等同,last-of-type和nth-last-of-type(1)等同。

nth-child,nth-of-type,first-of-type,last-of-type,nth-last-of-type,only-of-type等的区别


nth-child和nth-of-type在某些时候是效果是相同的

nth-child,nth-of-type,first-of-type,last-of-type,nth-last-of-type,only-of-type等的区别

不过二者还是有区别的

nth-child,nth-of-type,first-of-type,last-of-type,nth-last-of-type,only-of-type等的区别


可以简单的理解为,nth-child选择:更强调子元素(child),首先选择父元素第2个子元素 然后判断是否是p元素。

nth-of-type选择:更强调类型(type),首先是p类型,然后从中选第2个元素。

nth-last-child和nth-last-of-type,与上面类似。


only-child与only-of-type:选取属于其父元素的特定类型唯一子元素。

nth-child,nth-of-type,first-of-type,last-of-type,nth-last-of-type,only-of-type等的区别

nth-child,nth-of-type,first-of-type,last-of-type,nth-last-of-type,only-of-type等的区别

p:only-child: 侧重于child,选取的是唯一的子元素。

p:only-of-type:侧重于类型,在p类型中确定唯一。