nth-of-type 和 nth-child

163 阅读2分钟

nth-of-type 和 nth-child的区别

:nth-of-type(n) 选择器匹配属于父元素的特定类型的第N个子元素的每个元素
:nth-child(n) 选择器匹配属于父元素的第N个子元素,不论元素的类型

区别

1:用于元素节点

E:nth-of-type(n) E元素的父元素的子元素中第n个E元素匹配(不一定是E元素的父元素的第n个子元素)
E:nth-child(n) E元素的父元素的子元素第n个元素且是E元素才匹配

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <title></title>
    <style>
        p {
            color:blue;
        }
        p:nth-of-type(1){
            background-color:red;
        }
        h1:nth-of-type(1){
            background-color: yellow;
        }
        /*p:nth-child(1){*/
            /*background-color:red;*/
        /*}*/
        /*h1:nth-child(1){*/
            /*background-color: yellow;*/
        /*}*/
    </style>
</head>
<body>
<div>
    <h1 class="type">0</h1>
    <p class="type">1</p>
    <p class="type">2</p>
    <p class="type">3</p>
    <p class="type">4</p>
</div>
</body>
</html>

image.png

2.用于class节点

若classA的父元素的子元素的classA用于同一类型的元素节点 classA:nth-of-type(n) classA的父元素的子元素中第n个classA匹配(不一定是classA的父元素的第n个子元素)
classA:nth-child(n) classA元素的父元素的第n个子元素且是classA元素才匹配

<style>
        p {
            color:blue;
        }
        /*.type:nth-of-type(1){*/
            /*background-color:red;*/
        /*}*/
        .type:nth-child(1){
            background-color:#f00;
        }
    </style>
<div>
    <h1>0</h1>
    <p class="type">1</p>
    <p class="type">2</p>
    <p class="type">3</p>
    <p class="type">4</p>
</div>

image.png 若classA的父元素的子元素的classA用于不同类型的元素节点 classA:nth-of-type(n) classA的父元素的子元素中,每种类型的元素节点中第n个classA匹配(不一定是classA的父元素的第n个子元素,也不一定是只有一个)
classA:nth-child(n) classA元素的父元素的第n个子元素且是classA元素才匹配

<style>
        p {
            color:blue;
        }
        .type:nth-of-type(1){
            background-color:red;
        }
        /*.type:nth-child(1){*/
            /*background-color:#f00;*/
        /*}*/
    </style>

<div>
    <h1 class="type">0</h1>
    <p class="type">1</p>
    <p class="type">2</p>
    <p class="type">3</p>
    <p class="type">4</p>
</div>

image.png

说明:.type:nth-child(1)匹配的是type的父元素的子元素中第一个子元素且class是type的h1元素,.type:nth-of-type(1)匹配的是type的父元素的子元素中h1和p元素的第一个class是type的元素,即0和1。

总结

classA:nth-of-type(n) 匹配的是父元素的子元素中,每种类型的元素节点中第n个class类型是classA的元素(不一定是classA的父元素的第n个子元素,也不一定是只有一个)
classA:nth-child(n) 匹配的是父元素的第n个子元素且class类型是classA 转自