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

标签 html css css-selectors

<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

最佳答案

: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>

关于html - 如何选择具有特定类的最后一个元素,而不是父元素中的最后一个子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7298057/

相关文章:

javascript - 输入字段中的 'auto' 的值是多少

JavaScript 滚动到底部不起作用

html - 仅使用 CSS 设置宽度等于高度

javascript - Puppeteer $.eval 选择嵌套元素

html - 带有多行文本的标签内的中心复选框

javascript - 单击另一个选择框选项时,如何更改带有复选框中选项的选择框中的值

css - 页脚的负边距底部不起作用

html - 段落标签在打开时自行关闭

html - 如何将三个不同的段落垂直放在一个列表中?

css - 获取根选择器,并将其用作另一个选择器的一部分 - 在 Stylus 中