我有以下代码,我想使用 nth-child
选择特定的 class=title
但它似乎确实有效
<div class="block">
<div class="title"></div> <!-- first title here !-->
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="title"></div> <!-- second title here !-->
<div class="item"></div>
<div class="title"></div> <!-- third title here !-->
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
测试 1
.title:nth-child(3){
background-color: red;
}
预期结果第三个标题突出显示
,但实际输出是没有突出显示
测试 2
.title:nth-child(1){
background-color: red;
}
预期结果第一个标题突出显示
实际输出是第一个标题突出显示
我不确定为什么它不适用于另一个 child ,而它只适用于第一个 child ..
最佳答案
如果您确实想选择类名为 .title
的 div.block
的第三个子级,那么您必须知道 child index position 。在本例中,它是七而不是三。因此,您需要执行如下操作:
.title:nth-child(7){
background-color: red;
}
<小时/>
简而言之,在 div.block
中的 3
位置处没有类 title
的子级。
更新:
如果不知道子元素是否存在于指定位置,则无法使用 CSS 选择子元素。但使用 jQuery
是可能的。
$('.title:eq(2)') //This will search for the third child with the class .title
关于jquery - nth-child 只选择第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217303/