Select the last 3 child elements

后端 未结 3 833
一个人的身影
一个人的身影 2021-02-01 12:15

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

What I need is to

相关标签:
3条回答
  • 2021-02-01 12:50

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

    fiddle demonstration from Fabrício Matté

    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

    0 讨论(0)
  • 2021-02-01 12:57

    The accepted answer has the correct formula, but the explanation is wrong.

    So the correct CSS is (same as currently accepted answer):

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

    But here is the correct explanation of the math:

    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...
    
    0 讨论(0)
  • 2021-02-01 13:10

    This is possible with CSS3 selectors and formulas:

    .something a:nth-last-child(-n+3) { ... }
    

    You could also try using jQuery (example) or adding a specific class to the last three elements in your server-side code (it does not require JavaScript to be enabled in browsers and also works on older browsers that do not support CSS3).

    0 讨论(0)
提交回复
热议问题