当前位置: 首页 网络 正文伪类选择器:nth-child()与:nth-of-type()的使用方法及区别本文主要讨论伪类选择器 :nth-child()与:nth-of-type()的使用方法及区别,并引申:first-child的使用方法。

1. 简介本文主要讨论伪类选择器 :nth-child()与:nth-of-type()的使用方法及区别,并引申:first-child的使用方法

2. :nth-child(n)和:nth-of-type()的使用方法及区别

2.1 定义

匹配父级元素中的第n个子元素,子元素类型没有限制p:nth-child(2) 匹配在父级中位于第二位的p元素。换言之,匹配父级的第二个子元素,且该子元素为p。匹配父级元素中的第n个特定类型子元素p:nth-of-type(2) 匹配在父级p元素中的第二个元素。

2.2 用法使用语法相同。n可以是一个数字、一个关键字(odd、even)或者一个公式(an+ b)

2.3 区别:nth-child(n) 匹配时在父元素的所有子元素中匹配,不考虑子元素类型:nth-of-type(n) 匹配时在父元素的特定子元素中匹配具体区别见2.4

2.4 例子(1) 一般情况下

html head style p:nth-child(2) { background: #ff0000; /style /head body h1 This is a heading /h1 p The 1 paragraph. /p p The 2 paragraph. /p p The 3 paragraph. /p p The 4 paragraph. /p p The 5 paragraph. /p p The 6 paragraph. /p /body /html html head style p:nth-of-type(2) { background: #ff0000; /style /head body h1 This is a heading /h1 p The 1 paragraph. /p p The 2 paragraph. /p p The 3 paragraph. /p p The 4 paragraph. /p p The 5 paragraph. /p p The 6 paragraph. /p /body /html

(2) 子要素指的是直接子要素

html head style p:nth-of-type(1) { background: #ff0000; /style /head body h1 This is a heading /h1 p The 1 paragraph. /p p The 2 paragraph. /p p The 3 paragraph. /p div p The 3.1 paragraph. /p /div p The 4 paragraph. /p p The 5 paragraph. /p p The 6 paragraph. /p /body /html

(3)使用类名选择器时,:nth-of-type(n)会按照标签类型分组; :nth-child(n)不会

html head style .item:nth-of-type(1) background:#ff0000; /style /head body h1 This is a heading /h1 p The 1 paragraph. /p div The 2 paragraph. /div div The 3 paragraph. /div div The 4 paragraph. /div p The 5 paragraph. /p p The 6 paragraph. /p /body /html

3. :first-child 与 :nth-child(n)p:first-child 与 p:nth-child(1) 效果一致,可以说:nth-child(n)是 :first-child的扩展版