理想中的代码
<div>
<p class="testRed">A</p>
<p class="testBlue">B</p>
<p class="testRed">C</p>
<p class="testGreen">D</p>
</div>
<style>
.testRed:first-child{ //命中A
color:red
}
.testBlue:first-child{ //不命中
color:blue
}
.testBlue:first-of-type{ //理论上:命中B
color:blue
}
</style>
遇到的问题
同理看一下 nth-of-type
网上的回答
**StackFlow回答:**虽然任何元素一次可能只有一个子元素匹配:first-child,但它可以并且将有与:first-of-type伪类匹配的子元素与其拥有的子元素类型的数量一样多
答案揭晓
答案揭晓了:这个 first-of-type 的type是标签!!!,以后叫 first-of-label 好了,纯纯的大无语
总结:
1.[selector]:first-child:selector选中的是父节点的第一个孩子
举个🌰:
<section>
<div> <-- p 的父亲
<div>H</div>
<p class="b">A</p> <-- 第一个 p
<p> E </p>
</div>
</div> <-- p 的父亲
<p class="b">B</p> <-- 第一个 p
</div>
<span class="b">C</span>
<div >D</div>
</section>
<style>
p:first-of-type{
color:red;
}
//1. 找的 p 的父亲DOM
//2. 在p的兄弟节点中找出一起 p
//3. render -> 结果 A B 变红
</style>
再举个🌰:
<section>
<div> <-- p 的父亲
<div>H</div>
<p class="b">A</p> <-- 第一个 p
<p> E </p>
</div>
</div> <-- p 的父亲
<p class="b">B</p> <-- 第一个 p
</div>
<span class="b">C</span>
<div >D</div>
</section>
<style>
p:first-child{
color:red;
}
//1. 找的 p 的父亲DOM
//2. 在p的兄弟节点中找出一起 p
//3. 判断这个被找到P是不是 他爹的第一个娃
//3. render -> 结果 B 变红
</style>