我知道您可以使用 :last-child
选择最后一个 child ,或者使用 :nth-child
选择某个 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*/
}
最佳答案
您可以阅读更多here关于第 n 个 child ,但这基本上应该只用 CSS 来选择最后 3 个 child
#something a:nth-last-child(-n+3) {
/*declarations*/
}
fiddle Fabrício Matté 的示范
这只会选择那些为 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
其他一切都会返回一个负数
关于css - 选择最后 3 个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14268156/