:nth-child和:nth-of-type

来源:互联网 发布:淘宝神笔卖家推荐 编辑:程序博客网 时间:2024/05/16 09:25

在使用css的选择器中,经常会使用匹配到特定某个子元素,于是就想到了:nth-child和:nth-of-type。那么这两种到底有什么区别呢

定义

在MDN中的定义:

:nth-child(an+b) 这个 CSS 伪类匹配文档树中在其之前具有 an+b-1 个兄弟节点的元素,其中 n 为正值或零值。简单点说就是,这个选择器匹配那些在同系列兄弟节点中的位置与模式 an+b 匹配的元素。

(注意看两种定义的斜体字部分)

:nth-of-type(an+b) 这个 CSS 伪类 匹配那些在它之前有 an+b-1 个相同类型兄弟节点的元素,其中 n 为正值或零值。

:nth-child 只强调了同系列兄弟节点位置的关系

这个选择器匹配那些在同系列兄弟节点中的位置

:nth-of-type 则是更加精确到元素的类型

匹配那些在它之前有 an+b-1 个相同类型兄弟节点的元素

使用

:nth-child

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>nth</title>    <style>        p:nth-child(1) {            color:red;        }        p:nth-child(2) {            color:blue;        }        p:nth-child(3) {            color:pink;        }    </style></head><body>    <div class="content">        <p>1</p>        <div class="app">app</div>        <p>1</p>        <p>1</p>        <p>1</p>        <p>1</p>        <p>1</p>    </div></body></html>

效果如下:

这里写图片描述

可以看到,当p标签中间插入了别的标签时,兄弟节点的位置会发生变化,就会影响匹配到的内容。

:nth-of-type

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>nth</title>    <style>        p:nth-of-type(1) {            color:red;        }        p:nth-of-type(2) {            color:blue;        }        p:nth-of-type(3) {            color:pink;        }    </style></head><body>    <div class="content">        <p>第一个P</p>        <div class="app">app</div>        <p>第二个P</p>        <p>第三个P</p>        <p>第四个P</p>        <p>第五个P</p>        <p>第六个P</p>    </div></body></html>

效果如下:

这里写图片描述

虽然兄弟节点位置发生变化,但在精确匹配到类型之后,还是可以选中所需要的DOM元素。
个人认为一般情况下还是使用:nth-of-type比较靠谱