使用 css 选择倒数第二个元素

我已经知道了: last-child。但是有没有办法选择 div:

<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div> <!-- THIS -->
<div>c</div>
</div>

注意: 不使用 jQuery,只使用 CSS

135615 次浏览

在 CSS3课程中,你可以:

:nth-last-child(2)

见: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

Nth-last-child 浏览器支持:

  • Chrome 2
  • Firefox 3.5
  • 歌剧9.5,10
  • Safari 3.1,4
  • Internet Explorer 9

注意: 发布了这个答案,因为 OP 后来在评论中说他们需要选择 最后两个元素,而不仅仅是最后一个。


:nth-child CSS3选择器实际上比你想象的更有能力!

例如,这将选择 #container的最后两个元素:

#container :nth-last-child(-n+2) {}

但这只是一段美好友谊的开始。

#container :nth-last-child(-n+2) {
background-color: cyan;
}
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>

这将在每个 LI 之后添加一个逗号,在最后一个 LI 的第二个后面添加一个“或”,并使用带有 nth-last-child () : : after 的纯 CSS 在最后一个 LI 之后添加一个句点。

为了只影响到最后一个 LI 中的第二个,删除最后一个 CSS 条目,并将第二个 CSS 条目的(n + 3)内容设置为空(”)。

`<style>
/* Append endings to LIs.
Append "," to all but the last 2 LIs.
Append ", or" to the 2nd to the last LI.
Append "." to the last LI. */
article li:nth-last-child(n + 2)::after {
/* All but the last row. */
content: ', or';
}
article li:nth-last-child(n + 3)::after {
/* Overwrite all but the last two rows. */
content: ',';
}
article li:nth-last-child(1)::after {
content: '.';
}
</style>
<ul>
<li>Line 1</li>
<li>Line 2</li>
<li>Line 3</li>
<li>Line 4</li>
</ul>`

投降

  • 一号线,
  • 二号线,
  • 三号线,或者
  • 4号线。