该
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选择器会选择父项下每种类型的第一个/最后一个元素。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)