【问题标题】:Select the last 3 child elements选择最后 3 个子元素
【发布时间】:2012-12-25 10:40:03
【问题描述】:

我知道你可以用:last-child 选择最后一个孩子或用:nth-child 选择某个孩子(如果你知道他们的位置/编号)。

我需要的是在不知道可能有多少子元素的情况下选择最后 3 个子元素。

我知道有一个东西叫做:nth-last-child,但我真的不明白它是如何工作的。

为此:

<div id="something">

    <a href="images/x.jpg"  ><a/>
    <a href="images/x.jpg"  ><a/>
    <!-- More elements here -->
    <!-- ..... -->
    <!-- I need to select these: -->
    <a href="images/x.jpg"  ><a/>
    <a href="images/x.jpg"  ><a/>
    <a href="images/x.jpg"  ><a/>

</div> 

我需要这样的东西:

#something a:last-child{
   /* only now it selects the last <a> and the 2 <a>'s that come before*/ 
}

【问题讨论】:

  • :nth-last-child,与:nth-child基本相同,但从最后一个到第一个afaik。
  • 现在的问题是需要选择最后 3 个
  • P.S.结束标签是&lt;/div&gt; 而不是&lt;div/&gt;

标签: css css-selectors


【解决方案1】:

你可以阅读更多here关于 nth-last 孩子的信息,但这基本上应该可以用 CSS 选择最后 3 个孩子

#something a:nth-last-child(-n+3) {
    /*declarations*/
}

fiddle 来自 Fabrício Matté

的演示

这只会选择那些为 out N 表达式 (-n+3) 返回正数的行,并且由于我们使用的是 nth-last-child,它从最后一个到第一个计数, 所以从底部开始的第一行给出,

f(n) = -n+3
f(1) = -1+3 = 2 <- first row from the bottom
f(2) = -2+3 = 1 <- second row from the bottom
f(3) = -3+3 = 0 <- third row from the bottom

其他一切都将返回负数

【讨论】:

  • a -n 这当然会生成 3,2,1,0,-1 enz 所以只选择最后 3 个
  • 谢谢。它就像一个魅力。我已经为此苦苦挣扎了很长时间。
  • 为什么不使用 nth-child(n+3) ?对我来说似乎更简单......
  • @avia 因为 n+3 将选择从 4 到最后一个元素的每个元素。 f(n) = n+3 f(1) = 1+3 = 4 &lt;- fourth element f(2) = 2+3 = 5 &lt;- fifth element f(3) = 3+3 = 6 &lt;- sixth element
【解决方案2】:

这可以通过 CSS3 选择器和 formulas:

.something a:nth-last-child(-n+3) { ... }

您也可以尝试using jQuery (example) 或在服务器端代码的最后三个元素中添加一个特定的类(它不需要在浏览器中启用 JavaScript,也适用于不支持 CSS3 的旧浏览器)。

【讨论】:

    【解决方案3】:

    接受的答案有正确的公式,但解释是错误的。

    所以正确的 CSS 是(与当前接受的答案相同):

    #something a:nth-last-child(-n+3) {
        /*declarations*/
    }
    

    但这里是对数学的正确解释:

    f(n) = -n+3
    f(0) = -0+3 = 3 <- 3rd row from the bottom
    f(1) = -1+3 = 2 <- 2nd row from the bottom
    f(2) = -2+3 = 1 <- 1st row from the bottom
    f(3) = -3+3 = 0 <- nothing
    f(3) = -4+3 = -1 <- nothing
    etc...
    

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 2017-11-28
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      相关资源
      最近更新 更多