我知道你可以选择与上次寒意:last-child
。 现在我需要选择最后3个孩子的唯一的问题是孩子的量是不知道,所以我不能使用:nth-child
,我知道有一些东西是所谓的:nth-last-child
,但我真的不能明白这是怎么回事工作的
<div id="something">
<a href="images/x.jpg" ><a/>
<a href="images/x.jpg" ><a/>
<!-- here some more
and than 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 needs to select 2 more a's that are before this child */
}
你可以阅读更多这里关于第n-最后一个孩子,但是这应该基本上做到只用CSS选择最后的3个孩子的把戏
#something a:nth-last-child(-n+3) {
/*declarations*/
}
小提琴从法布里西奥磨砂示范
这只会选择那些对于返回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
一切将返回一个负数
这是可能的CSS3选择器和公式 :
.something a:nth-last-child(-n+3) { ... }
您也可以尝试使用jQuery(例如)或添加特定类在你的服务器端代码的最后三个元素(它不需要JavaScript在浏览器中启用,也适用于不支持CSS3旧的浏览器)。
该接受的答案有正确的公式,但对此的解释是错误的。
所以,正确的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...