css3中nth-child()的用法示例代码
<p>nth-child(n)是css3中的一种选择器,它的作用是匹配属于其父元素的第n个元素,不论元素的类型。重点是“不论元素的类型这句话”,好多人容易误解这句话。</p><p>现在提出一个需求,如下图所示,将第二行和第三行的字体颜色改为红色和蓝色</p>
<div class="jb51code"><pre class="brush:css;"><div class="father1">
<p>1234</p>
<p>12345</p>
<p>12345</p>
</div></pre></div>
<p>css代码实现:很容易实现,利用p:nth-child(2)和p:nth-child(3)分别选中第2和第3个元素不就可以了吗?</p>
<div class="jb51code"><pre class="brush:css;">.father1 {
width:300px;
height:300px;
background-color: aqua;
p:nth-child(2) {
color:red;
}
p:nth-child(3) {
color:blue;
}
}</pre></div>
<p>看效果图:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202401/2024011915132057.png" /></p>
<p>我现在又提出了一个新的需求:还是把将第二行和第三行的字体颜色改为红色和蓝色,要求使用nth-child(n)选择器实现</p>
<div class="jb51code"><pre class="brush:css;"><div class="father1">
<img src="./2.jpg" alt="">
<p>12345</p>
<span>12345</span>
</div></pre></div>
<p>那么有的人会这样去写css代码:</p>
<div class="jb51code"><pre class="brush:css;">.father1 {
width:300px;
height:300px;
background-color: aqua;
p:nth-child(1) {
color:red;
}
span:nth-child(1) {
color:blue;
}
}</pre></div>
<p>来看效果图:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202401/2024011915132058.jpg" /></p>
<p>怎么没有生效呢?咱们代码写的也没有问题啊,p:nth-child(1):p标签中排列的第一个元素,span:nth-child(1):span标签中排列的第一个元素嘛?没有问题啊,怎么回事呀?</p>
<p><strong>要注意</strong>:不论其元素类型。nth-child(n)指的是在父元素中所有的元素的顺序,上述html代码中,div是父元素,img,p和span标签都是div的子元素,p排在第2个,span排在第3个,这才是对n的正确理解。</p>
<p>咱么试一试,改动一下css代码:</p>
<div class="jb51code"><pre class="brush:css;">.father1 {
width:300px;
height:300px;
background-color: aqua;
p:nth-child(2) {
color:red;
}
span:nth-child(3) {
color:blue;
}
}</pre></div>
<p>效果图:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202401/2024011915132059.jpg" /></p>
頁:
[1]