说明
first-child、last-child、nth-child(n)、nth-child(2n)、nth-child(2n-1)、nth-child(odd)、nth-child(even)、nth-last-child(3)(倒数第三个)
first-child选择器用于选取属于其父元素的 首个 子元素的指定选择器。
last-child选择器用于选取属于其父元素的 最后一个 子元素的指定选择器。
nth-last-child(3)择器用于选取属于其父元素的 倒数第三个 子元素的指定选择器。
注意点: 选择器匹配属于其父元素的第 N 个子元素,不论元素的类型。
1、先找到该伪类调用者(元素)的父类
2、其次找到父类下的第n个子元素
3、最后看该子元素是不是1中的伪类调用者,如果是,则应用css,否则不应用
有时候first-child或者nth-child(1) 不起作用的原因,如下:
/*
此时first-child不起作用,
是因为.tap_con的父元素container的第一个子元素是.top,此时找到第一个子元素,但是其并不是.tab_con
*/
<style>
.tab_con:first-child{
background:#090 !important;
}
.tab_con:nth-child(1){
background:#090 !important;
}
</style>
<div id="container">
<div class="top">
</div>
<div class="tab_con">
</div>
<div class="tab_con">
</div>
</div>
本文介绍了CSS中的几个子元素选择器,如first-child、last-child和nth-child(n)等,以及如何正确使用它们来选取特定的子元素。文章提到了在某些情况下,如.first-child不生效的问题,可能是因为选择器没有匹配到正确的父元素的第一个子元素。示例代码展示了当tapping_con是container的第二个子元素时,first-child和nth-child(1)不会生效的情况。
861

被折叠的 条评论
为什么被折叠?



