标签:nth-child、nth-of-type、伪类选择器
对于 :nth-child :
先看下面的一段代码:
<style>
p:nth-child(1){
border: 1px solid;
}
</style>
<div class="c1">
<div class="c11">
<p class="pp">1</p>
<p class="pp">2</p>
</div>
<p class="pp">3</p>
<p class="pp">4</p>
</div>
<div class="c2">
<p class="pp">5</p>
<p class="pp">6</p>
</div>运行效果:
接着,稍微调整一下代码:
<style>
p:nth-child(1){
border: 1px solid;
}
</style>
<div class="c1">
<p class="pp">3</p>
<div class="c11">
<p class="pp">1</p>
<p class="pp">2</p>
</div>
<p class="pp">4</p>
</div>
<div class="c2">
<p class="pp">5</p>
<p class="pp">6</p>
</div>运行效果:
结论:
对于p:nth-child选择器,在简单白话文中,意味着选择一个元素如果:
这是个段落元素
这是父标签的第二个孩子元素
对于 :nth-of-type :
<style>
p:nth-of-type(1){
border: 1px solid #ff0000;
}
</style>
<div class="c1">
<div class="c11">
<p class="pp">1</p>
<p class="pp">2</p>
</div>
<p class="pp">3</p>
<p class="pp">4</p>
</div>
<div class="c2">
<p class="pp">5</p>
<p class="pp">6</p>
</div>运行结果:
结论:
p:nth-of-type(1)表示父标签下的第1个p元素,而不论在p元素之前还有什么元素。比如下面这样:
<style>
p:nth-of-type(1){
border: 1px solid #ff0000;
}
</style>
<div class="c1">
<div class="c11">
<p class="pp">1</p>
<p class="pp">2</p>
</div>
<span>something</span>
<div>something</div>
<p class="pp">3</p>
<p class="pp">4</p>
</div>
<div class="c2">
<p class="pp">5</p>
<p class="pp">6</p>
</div>运行结果:
对比:nth-child和:nth-of-type之间的差异:
p:nth-child(1),是指元素必须是p元素,而且在其父元素中排第一个,也就是其父元素的第一个直接子节点。如果有任何非p元素在它之前出现,则选择器失效。
p:nth-of-type(1),是指元素必须是p元素,并且在其父元素的所有p子元素中排第一个(非p子元素会被忽略),不论在该元素之前有多少个非p子元素出现。
当然,在:nth-child、:nth-of-type作用的选择器类型不单单是标签选择器,可以是其它的css选择器。也就是上述例子中的p:nth-child、p:nth-of-type可以改成类选择器.pp:nth-child、.pp:nth-of-type。
本文出自 “isymu” 博客,请务必保留此出处http://isymu.blog.51cto.com/1460577/1663331
标签:nth-child、nth-of-type、伪类选择器
原文地址:http://isymu.blog.51cto.com/1460577/1663331