【问题标题】:CSS selector for selecting the last two children, without knowing how many items are in the list用于选择最后两个孩子的 CSS 选择器,不知道列表中有多少项目
【发布时间】:2014-04-18 17:41:21
【问题描述】:

我有一个无序列表。它有时包含 4、5、6 或 7 个项目。我想知道是否有 CSS 选择器来选择最后两项。我意识到:last-child 会给我最后一件物品。是否有“倒数第二个孩子”选择器?还是“孩子数 -2”选择器?

HTML:

<ul>
  <li>First Item</li>
  <li>Second Item</li>
  <li>Second from Last Item</li>
  <li>Last Item</li>
<ul>

CSS:

ul li:last-child, ul li:last-child-1 {
  // Do something
}

我意识到:last-child-1 不是选择器,但我希望那里有类似的东西。任何帮助将不胜感激。

【问题讨论】:

标签: css css-selectors


【解决方案1】:
ul li:nth-last-child(-n + 2) {
    /* .. */
}

【讨论】:

    【解决方案2】:

    :nth-last-child

    http://jsfiddle.net/pQmXM/1/

    ul li:nth-last-child(1),
    ul li:nth-last-child(2)
    {
        color: red;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 2014-04-26
      相关资源
      最近更新 更多