选择last-child
器用于选择父元素的最后一个子元素。它不能用于选择给定父元素下具有特定类的最后一个子元素。
复合选择器的另一部分(附加在 之前:last-child
)指定了最后一个子元素必须满足的额外条件才能被选中。在下面的代码片段中,您将看到所选元素如何根据复合选择器的其余部分而有所不同。
.parent :last-child{ /* this will select all elements which are last child of .parent */
font-weight: bold;
}
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/
background: crimson;
}
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/
color: beige;
}
<div class='parent'>
<div class='child'>Child</div>
<div class='child'>Child</div>
<div class='child'>Child</div>
<div>Child w/o class</div>
</div>
<div class='parent'>
<div class='child'>Child</div>
<div class='child'>Child</div>
<div class='child'>Child</div>
<div class='child-2'>Child w/o class</div>
</div>
<div class='parent'>
<div class='child'>Child</div>
<div class='child'>Child</div>
<div class='child'>Child</div>
<p>Child w/o class</p>
</div>
为了回答您的问题,下面将li
设置背景颜色为红色的最后一个子元素。
li:last-child{
background-color: red;
}
但是以下选择器不适用于您的标记,因为last-child
即使class='complete'
它是li
.
li.complete:last-child{
background-color: green;
}
如果(且仅当)li
您的标记中的最后一个也有class='complete'
.
要在评论中解决您的查询:
@Harry我觉得很奇怪: .complete:last-of-type 不起作用,但是 .complete:first-of-type 确实起作用,无论它的位置如何,它都是父元素。谢谢你的帮助。
选择器.complete:first-of-type
在小提琴中起作用,因为它(即带有 的元素class='complete'
)仍然是li
父元素中类型的第一个元素。尝试添加<li>0</li>
作为下的第一个元素ul
,你会发现它first-of-type
也失败了。这是因为first-of-type
andlast-of-type
选择器选择父级下每种类型的第一个/最后一个元素。
有关选择器如何工作的更多详细信息,请参阅此线程中BoltClock 发布的答案。这是最全面的:)