css - 选择最后 3 个子元素

标签 css css-selectors

我知道您可以使用 :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/

相关文章:

css - 是否有 CSS 父级选择器?

css - CSS类选择器、id选择器的语法?

javascript - Foundation 5 pinterest 风格的模态弹出窗口

html - Internet Explorer 中的 CSS 下拉菜单偏移,其他工件也是如此

html - 修改标题 css 以在两个不同位置包含文本

css - 我可以合并 :nth-child() or :nth-of-type() with an arbitrary selector?

php - 表中最后两行之间的空间

CSS 属性选择器 + 后代在 Webkit 中出现错误?

css - 如何在超大屏幕下获得自定义背景?

php - 仅在 chrome 的图像 slider 中对齐图像