两个都是在某个父容器下的子容器选择器.
div h1:nth-child(n) & div h1:nth-of-type(n)
它们之间有什么区别呢?
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>
界面
开始测试:
当 n = 1 的时候
.nth-child h1:nth-child(1) {
background: orange;
}
.nth-of-type h1:nth-of-type(1) {
background: orange;
}
猜测
在第一个
div.nth-child
里 , 第一个元素是 h1 ,变黄应该没毛病.
在第二个div.nth-of-type
里,第一个元素也是 h1 ,变黄应该也没毛病.
结果:
结果符合猜测!
当 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 ,应该没有元素变黄.
在第二个div.nth-of-type
里,第二个元素也不是 h1 同样是 p ,应该也没有元素变黄吧
结果并不符合猜测.
第一个 div ,也就是nth-child
猜对了,但是后面的nth-of-type
则猜错了.
第二个里面有变黄的,变黄的是 n = 4 的 h1 元素.
好像有点意思了h1:nth-of-type 好像是只按h1元素排序,不关心其他元素??
而h1:nth-child 所有的子元素都在关心,同时也要关心h1元素的位置??
证明猜测
如果对 nth-child
和 ntc-of-type
的猜测是对的.
那么在n = 3时.
第一个 div.nth-child 由于第三个元素不是h1 所以,没有背景颜色.
而第二个 div.nth-of-type 除去其他不是h1元素的影响,剩下的h1中有第3个h1元素,应该是index:5的那个元素亮起来?
.nth-child h1:nth-child(3) {
background: orange;
}
.nth-of-type h1:nth-of-type(3) {
background: orange;
}
猜测是对了,结果符合预期.
最后总结:
对于 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>