【问题标题】:Is it possible to select the last n items with nth-child?是否可以选择带有 nth-child 的最后 n 个项目?
【发布时间】:2011-06-18 04:25:33
【问题描述】:

使用标准列表,我试图选择最后 2 个列表项。我有 An+B 的各种排列,但似乎没有选择最后 2 个:

li:nth-child(n+2) {} /* selects from the second onwards */
li:nth-child(n-2) {} /* selects everything */
li:nth-child(-n+2) {} /* selects first two only */
li:nth-child(-n-2) {} /* selects nothing */

我知道有一个新的 CSS3 选择器,例如 :nth-last-child(),但如果可能的话,我更喜欢在更多浏览器中工作的东西(不要特别关心 IE)。

【问题讨论】:

  • 尽管有 IE,但浏览器对 :nth-last-child() 的支持与 :nth-child() according to quirksmode.org 大致相同。此外,:nth-child():nth-last-child() 都是在 CSS3 中引入的,在这个意义上既不是旧的也不是新的。
  • nth-child总结了很多有用的技巧css-tricks

标签: css css-selectors


【解决方案1】:

这将选择列表的最后两个 iem:

li:nth-last-child(-n+2) {color:red;}
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>

【讨论】:

  • 是的,但是您使用的是:nth-last-child(),这已经被提及了。
  • (-n+2) => 这就是我要找的。谢谢
  • 这应该是公认的答案,是的,已经提到了 nth-last-child,但不完全是 (-n+b) 是一个很酷的技巧
【解决方案2】:

nth-last-child 听起来像是专门为解决这个问题而设计的,所以我怀疑是否有更兼容的替代方案。不过,支持看起来 pretty decent

【讨论】:

  • 感谢链接 - 看起来 nth-child 支持实际上与 nth-last-child 相同(我确信 IE8 支持 nth-child 但可能不支持)。
【解决方案3】:

:nth-last-child(-n+2) 应该可以解决问题

【讨论】:

    【解决方案4】:

    由于nth-child 的语义定义,如果不包括所涉及的元素列表的长度,我看不出这是怎么可能的。语义的重点是允许将一堆子元素分成重复组(edit - 感谢 BoltClock)或某个固定长度的第一部分,然后是“其余部分”。你有点想要相反的东西,这就是nth-last-child 给你的。

    【讨论】:

    • 使用:nth-child(),您可以通过指定:nth-child(-n+m)来选择第一个m元素。
    • @BoltClock 我将不得不考虑一下......哦,是的,你是对的。显然,无论如何,我都无法就委员会在发明 CSS3 选择器时的意图发表严肃的声明 :-)
    【解决方案5】:

    如果您在项目中使用 jQuery,或者愿意包含它,您可以通过其选择器 API 调用 nth-last-child(这是模拟的跨浏览器)。 Here is a linknth-last-child 插件。如果您采用这种方法定位您感兴趣的元素:

    $('ul li:nth-last-child(1)').addClass('last');
    

    然后再次设置last 类而不是nth-childnth-last-child 伪选择器的样式,您将获得更加一致的跨浏览器体验。

    【讨论】:

      猜你喜欢
      • 2013-04-04
      • 2021-09-15
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      相关资源
      最近更新 更多