兩個都是在某個父容器下的子容器選擇器.
div h1:nth-child(n) & div h1:nth-of-type(n)
它們之間有什么區(qū)別呢?
HTML代碼
<!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>Document</title>
<style>
.container > div {
border: 1px solid red;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<h3>nth-child 測試</h3>
<div class="nth-child">
<h1>h1 ntc-child index : 1</h1>
<p>p ntc-child index : 2</p>
<p>p ntc-child index : 3</p>
<h1>h1 ntc-child index : 4</h1>
<h1>h1 ntc-child index : 5</h1>
</div>
</div>
<h3>ntc-of-type 測試</h3>
<div class="nth-of-type">
<h1>h1 nth-of-type index: 1</h1>
<p>p nth-of-type index : 2</p>
<p>p nth-of-type index : 3</p>
<h1>h1 nth-of-type index: 4</h1>
<h1>h1 nth-of-type index: 5</h1>
</div>
</body>
</html>
界面
開始測試:
當(dāng) n = 1 的時候
.nth-child h1:nth-child(1) {
background: orange;
}
.nth-of-type h1:nth-of-type(1) {
background: orange;
}
猜測
在第一個
div.nth-child
里 , 第一個元素是 h1 ,變黃應(yīng)該沒毛病.
在第二個div.nth-of-type
里,第一個元素也是 h1 ,變黃應(yīng)該也沒毛病.
結(jié)果:
結(jié)果符合猜測!
當(dāng) n = 2 的時候
.nth-child h1:nth-child(2) {
background: orange;
}
.nth-of-type h1:nth-of-type(2) {
background: orange;
}
猜測
在第一個
div.nth-child
里 , 第二個元素不是 h1 而是 p ,應(yīng)該沒有元素變黃.
在第二個div.nth-of-type
里,第二個元素也不是 h1 同樣是 p ,應(yīng)該也沒有元素變黃吧
結(jié)果并不符合猜測.
第一個 div ,也就是nth-child
猜對了,但是后面的nth-of-type
則猜錯了.
第二個里面有變黃的,變黃的是 n = 4 的 h1 元素.
好像有點意思了h1:nth-of-type 好像是只按h1元素排序,不關(guān)心其他元素??
而h1:nth-child 所有的子元素都在關(guān)心,同時也要關(guān)心h1元素的位置??
證明猜測
如果對 nth-child
和 ntc-of-type
的猜測是對的.
那么在n = 3時.
第一個 div.nth-child 由于第三個元素不是h1 所以,沒有背景顏色.
而第二個 div.nth-of-type 除去其他不是h1元素的影響,剩下的h1中有第3個h1元素,應(yīng)該是index:5的那個元素亮起來?
.nth-child h1:nth-child(3) {
background: orange;
}
.nth-of-type h1:nth-of-type(3) {
background: orange;
}
猜測是對了,結(jié)果符合預(yù)期.
最后總結(jié):
對于 h1:nth-child 來說:和h1同一層次的其他子元素也全部參與計算.
<div class="nth-child">
<h1>h1 ntc-child index : 1</h1>
<p>p ntc-child index : 2</p>
<p>p ntc-child index : 3</p>
<h1>h1 ntc-child index : 4</h1>
<h1>h1 ntc-child index : 5</h1>
</div>
而對于 h1:nth-of-type 來說:css 篩選器首先會排除不是h1元素的影響.只專注h1元素.
<div class="nth-of-type">
<h1>h1 nth-of-type index: 1</h1>
<p>p nth-of-type index : 2</p>
<p>p nth-of-type index : 3</p>
<h1>h1 nth-of-type index: 4</h1>
<h1>h1 nth-of-type index: 5</h1>
</div>
變換成
<div class="nth-of-type">
<h1>h1 nth-of-type index: 1</h1>
<h1>h1 nth-of-type index: 4</h1>
<h1>h1 nth-of-type index: 5</h1>
</div>