如何选择具有特定类的最后一个元素,而不是父级中的最后一个子元素?

新手上路,请多包涵
<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>

我想选择 #com19

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

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

只要我确实有另一个 div.something 作为commentList 中的实际最后一个孩子,这不起作用。在这种情况下是否可以使用 last-child 选择器来选择 article.comment 的最后一次出现?

jsFiddle

原文由 matt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

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

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

根据@BoltClock 的评论,这仅检查最后一个 article 元素,而不是 .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>

原文由 Chris 发布,翻译遵循 CC BY-SA 4.0 许可协议

我想最正确的答案是:使用 :nth-child (或者,在这种特定情况下,它的对应物 :nth-last-child )。大多数人只知道这个选择器的第一个参数是根据 n 的计算获取一系列项目,但它也可以采用“[任何 CSS 选择器]”的第二个参数。

你的场景可以用这个选择器来解决: .commentList .comment:nth-last-child(1 of .comment)

但是技术上正确并不意味着你可以使用它,因为这个选择器目前只在 Safari 中实现。

进一步阅读:

原文由 hurrtz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题