CSS :nth-child与:nth-of-type选择器
2017-08-10 15:13
791 查看
首先看一个例子:
<html> <head> <style type="text/css"> p:nth-child(2){color:blue;} p:nth-of-type(2){color:red;} </style> </head> <body> <div> <span>span 1</span> <p class="p1">paragraph 1</p> <P class="p2">paragraph 2</p> </div> </body> </html>
以上代码执行的结果为:
从结果看出,第1个p标签的文字被设置为了蓝色,而第2个p标签被设置为了红色。这时我们就知道:nth-child与:nth-of-type的作用了:
:nth-child(n)伪类选择器选择属于其父元素的第n个子元素,不关心子元素的类型。
上面例子中的p:nth-child(2)表示的就是p元素的父元素div下的第2个子元素,也就是class="p1"的p元素。
而:nth-of-type(n)伪类选择器选择属于其父元素的指定类型的第n个子元素,关心子元素的类型。
上面例子中的p:nth-of-type(2)表示的就是p元素的父元素div下的第2个p元素,也就是class="p2"的p元素。
在实际使用中,可以采用公式(an+b)对元素进行选择(n从0开始),例如:
a:nth-child(n+4),选择第4个及之后的a元素;
a:nth-child(-n+4),选择第4个及之前的a元素;
a:nth-child(2n+4),选择第4、6、8...个a元素;
等等
另外,还可以使用even、odd进行奇偶元素的选择(元素的下标从1开始):
a:nth-child(even),选择偶数位的a元素;
a:nth-child(odd),选择奇数位的a元素。
以上,欢迎补充斧正。
相关文章推荐
- CSS nth-child、first-child、last-child、nth-of-type、first-of-type和last-of-type选择器使用
- CSS3伪类选择器:nth-child(n)及:nth-of-type(n)使用区别探究总结
- css 伪类选择器 :nth-child(n) 与:nth-of-type(n)的区别
- CSS nth-child、first-child、last-child、nth-of-type、first-of-type和last-of-type选择器使用
- HTML5基础加强css样式篇(结构化伪类选择器:nth-child和nth-of-type比较)(十二)
- 【Web前端】CSS 选择器之 last-child 与 last-of-type
- CSS 选择器 :last-child与:last-of-type的区别
- CSS3选择器:nth-child和:nth-of-type之间的差异
- CSS中nth-child和nth-of-type的简单使用
- [css3]CSS3选择器:nth-child和:nth-of-type之间的差异
- css伪类选择器之:first-child和:first-of-type
- CSS3的nth-child() 和nth-of-type()选择器,表格奇偶行变色
- CSS3选择器:nth-child和:nth-of-type之间的差异
- CSS3子元素选择方法nth-child和nth-of-type
- CSS3选择器:nth-child和:nth-of-type之间的差异
- css中的first-child nth-child nth-last-child() 和:nth-of-type(n)
- css nth-child(n)和nth-of-type(n)区别
- 伪类选择器之结构选择器::noth-child(n)/:nth-of-type(n)
- css3 - 选择器first-child、last-child、nth-child、nth-last-child、nth-of-type
- css:nth-of-type()选择器用法