CSS last-child 选择器:选择特定类的最后一个元素,而不是父级中的最后一个孩子? [英] CSS last-child selector: select last-element of specific class, not last child inside of parent?

查看:60
本文介绍了CSS last-child 选择器:选择特定类的最后一个元素,而不是父级中的最后一个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<article class="comment" id="com21"></article><article class="comment" id="com20"></article><article class="comment" id="com19"></article><div class="something">你好</div>

我要选择 #com19 吗?

.comment {宽度:470px;边框底部:1px 虚线 #f0f0f0;底边距:10px;}.comment:last-child {边框底部:无;保证金底部:0;}

只要我在 commentList 中有另一个 div.something 作为实际的最后一个子项,那就行不通了.在这种情况下是否可以使用 last-child 选择器来选择 article.comment 的最后一个外观?

jsFiddle

解决方案

:last-child 仅当所讨论的元素是容器的最后一个子元素而不是特定类型的最后一个子元素时才有效的元素.为此,您需要 :last-of-类型

http://jsfiddle.net/C23g6/3/

根据@BoltClock 的评论,这只是检查最后一个 article 元素,而不是具有 .comment 类的最后一个元素.

body {背景:黑色;}.评论 {宽度:470px;边框底部:1px 虚线 #f0f0f0;底边距:10px;}.comment:last-of-type {边框底部:无;底边距:0;}

<article class="comment" id="com21"></article><article class="comment" id="com20"></article><article class="comment" id="com19"></article><div class="something">你好</div>

<div class="commentList">
   <article class="comment " id="com21"></article>
   <article class="comment " id="com20"></article>
   <article class="comment " id="com19"></article>
   <div class="something"> hello </div>
</div>

I want to select #com19 ?

.comment {
    width:470px;
    border-bottom:1px dotted #f0f0f0;
    margin-bottom:10px;
}

.comment:last-child {
    border-bottom:none;
    margin-bottom:0;
}

That does not work as long as I do have another div.something as actual last child in the commentList. Is it possible to use the last-child selector in this case to select the last appearance of article.comment?

jsFiddle

解决方案

:last-child only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want :last-of-type

http://jsfiddle.net/C23g6/3/

As per @BoltClock's comment, this is only checking for the last article element, not the last element with the class of .comment.

body {
  background: black;
}

.comment {
  width: 470px;
  border-bottom: 1px dotted #f0f0f0;
  margin-bottom: 10px;
}

.comment:last-of-type {
  border-bottom: none;
  margin-bottom: 0;
}

<div class="commentList">
  <article class="comment " id="com21"></article>

  <article class="comment " id="com20"></article>

  <article class="comment " id="com19"></article>

  <div class="something"> hello </div>
</div>

这篇关于CSS last-child 选择器:选择特定类的最后一个元素,而不是父级中的最后一个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆