You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用:nth-last-child选择倒数第二行及倒数第三行?

使用:nth-last-child选择指定的
元素

要选中6个

里从底部数第2和第3个元素,直接用逗号分隔两个:nth-last-child选择器即可,具体CSS代码如下:

div:nth-last-child(2),
div:nth-last-child(3) {
  /* 可自定义选中后的样式,比如高亮效果 */
  background-color: #f0f8ff;
  border-left: 3px solid #2196f3;
}

完整效果示例代码

<div>row1 - not selected</div>
<div>row2 - not selected</div>
<div>row3 - not selected</div>
<div>row4 - selected</div>
<div>row5 - selected</div>
<div>row6 - not selected</div>

<style>
div:nth-last-child(2),
div:nth-last-child(3) {
  background-color: #f0f8ff;
  border-left: 3px solid #2196f3;
}
</style>

选择器原理

  • :nth-last-child(n) 从父元素的最后一个子元素开始反向计数,n代表目标位置的序号。
  • div:nth-last-child(3) 对应倒数第3个
    (即row4),div:nth-last-child(2) 对应倒数第2个
    (即row5),用逗号组合就能同时选中这两个目标元素。

内容的提问来源于stack exchange,提问作者blacknighttext

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:45:27