选择最后3个孩子

Ivo*_*Ivo 37 css css-selectors

我知道你可以选择最后的寒意:last-child.现在我需要选择最后3个孩子唯一的问题是孩子的数量不知道所以我不能使用:nth-child,我知道有一些被称为: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> 
Run Code Online (Sandbox Code Playgroud)

所以现在我需要这样的东西:

#something a:last-child{
   /* only now it selects the last <a> and the 2 <a>'s that come before*/ 
}
Run Code Online (Sandbox Code Playgroud)

Bas*_*nni 101

你可以在这里阅读更多关于最后一个孩子的内容,但这基本上应该是用CSS选择最后3个孩子的伎俩

#something a:nth-last-child(-n+3) {
    /*declarations*/
}
Run Code Online (Sandbox Code Playgroud)

来自FabrícioMatté的小提琴演示

这只会选择那些对于返回N个表情正数(-n + 3)行,因为我们使用的是第n个最后的孩子,它是从最后数到第一,所以第一排从底部给出,

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
Run Code Online (Sandbox Code Playgroud)

其他一切都会返回一个负数

  • 打败我一分钟:P [小提琴](http://jsfiddle.net/6BV3K/)为您的答案 (2认同)

pra*_*dym 6

CSS3选择器和公式可以实现:

.something a:nth-last-child(-n+3) { ... }
Run Code Online (Sandbox Code Playgroud)

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


Ric*_*uff 5

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

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

#something a:nth-last-child(-n+3) {
    /*declarations*/
}
Run Code Online (Sandbox Code Playgroud)

但这是数学的正确解释:

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...
Run Code Online (Sandbox Code Playgroud)