选择最后3个子元素 [英] Select the last 3 child elements

查看:62
本文介绍了选择最后3个子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know you can select the last child with :last-child or a certain child with :nth-child (if you know their position/number).

我需要选择最后3个孩子,而不知道可能有多少个孩子元素.

What I need is to select the last 3 children without knowing how many child elements there could be.

我知道有一种叫做:nth-last-child的东西,但是我真的无法理解它是如何工作的.

I know there is something that's called :nth-last-child but I cant really understand how it is working.

为此:

<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*/ 
}

推荐答案

您可以在此处关于第n个倒数第二个孩子,但这基本上应该可以完成选择仅三个CSS的最后三个孩子的技巧

You can read more here about nth-last child, but this should basically do the trick of selecting the last 3 children with just CSS

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

FabrícioMatté

这只会选择返回正数的N行(-n + 3)的那些行,由于我们使用的是nth-last-child,所以从倒数到第一个进行计数, 所以从底部开始的第一行给出

This will only select those rows returning a positive number for out N expression (-n+3), and since we are using nth-last-child, it's counting from last to first, so first rows from bottom gives,

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

其他所有内容都将返回负数

everything else will return a negative number

这篇关于选择最后3个子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆