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

330 阅读2分钟

E:nth-child(n)

n可以是数字,可以是表达式,可以是odd可以even n为数字时:代表几个 n为表达式时:例如(2n+1)表示(n = 1,2,3,4...)括号对应的第几,第(3,5,7,9...)元素都时满足的 n为odd,even:表示奇数和偶数

以上和本问题无关 Talk is cheap,let's show the code

html

<h1>div-1</h1>
<div>
    <p class="text">p 1</p>
    <span class="text">span 1 have class = text</span>
    <p class="text">p 2</p>
    <span>span 2 no class = text</span>
    <p class="text">p 3</p>
    <span class="text">span 3 have class = text</span>
</div>
<h1>div-2</h1>
<div>
    <p class="text">p 1</p>
    <p class="text">p 2</p>
    <span class="text">span 1 have class = text</span><br />
    <span>span 2 no class = text</span>
    <p class="text">p 3</p>
    <span class="text">span 3 have class = text</span>
</div>

css

p:nth-child(1),p:nth-child(2),p:nth-child(3){
    color:red;
}

效果

解释:所有的子标签下第1,2,3为p标签的元素添加一个color:red;样式。 div p:nth-child(1):表示在div标签下的子元素 .text p:nth-child(1):表示在class=text标签下的子元素

E:nth-of-type(n)

和上面一样的html

<h1>div-1</h1>
<div>
    <p class="text">p 1</p>
    <span class="text">span 1 have class = text</span>
    <p class="text">p 2</p>
    <span>span 2 no class = text</span>
    <p class="text">p 3</p>
    <span class="text">span 3 have class = text</span>
</div>
<h1>div-2</h1>
<div>
    <p class="text">p 1</p>
    <p class="text">p 2</p>
    <span class="text">span 1 have class = text</span><br />
    <span>span 2 no class = text</span>
    <p class="text">p 3</p>
    <span class="text">span 3 have class = text</span>
</div>

css

.text:nth-of-type(1){
	background-color: blue;
}
.text:nth-of-type(2){
	background-color: red;
}
.text:nth-of-type(3){
	background-color: yellow;
}

效果:

解释:子元素中html标签各不相同的元素各自排名,排名和E都对应正确才为其添加样式

总结:nth-child排名是所有子元素进行排名,nth-of-type会根据子元素的元素类型各自排名