:最后一个子元素不能按预期工作?

:最后一个子元素不能按预期工作?,第1张

:最后一个子元素不能按预期工作?

last-child
选择器用于选择父的最后一个子元素。它不能用于选择给定父元素下具有特定类的最后一个子元素。

复合选择器的另一部分(位于之前

:last-child
)指定了附加条件,最后一个子元素必须按顺序满足才能被选择。在下面的代码段中,您将看到所选元素如何根据复合选择器的其余部分而有所不同。

.parent :last-child{   font-weight: bold;}.parent div:last-child{   background: crimson;}.parent div.child-2:last-child{   color: beige;}<div >  <div >Child</div>  <div >Child</div>  <div >Child</div>  <div>Child w/o class</div></div><div >  <div >Child</div>  <div >Child</div>  <div >Child</div>  <div >Child w/o class</div></div><div >  <div >Child</div>  <div >Child</div>  <div >Child</div>  <p>Child w/o class</p></div>

为了回答您的问题,下面将

li
使用背景颜色将最后一个子元素设置为红色。

li:last-child{    background-color: red;}

但是以下选择器将不适用于您的标记,因为即使它是,

last-child
也没有。
``li

li.complete:last-child{    background-color: green;}

如果(且仅当)

li
标记中的最后一个也有时,它才有效


要在评论中解决您的查询:

@Harry我觉得很奇怪:.complete:last-of-type不起作用,但是.complete:first-of-type起作用,而不管它是父元素的位置如何。谢谢你的帮助。

选择器

.complete:first-of-type
之所以起作用,是因为选择器(即带有的元素
)仍然
li
是父级中类型的第一个元素。尝试添加
<li>0</li>
作为的第一个元素
ul
,您还会发现它
first-of-type
也失败了。这是因为
first-of-type
last-of-type
选择器会选择父项下每种类型的第一个/最后一个元素。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5675800.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存