Select the last 3 child elements

CssCss Selectors

Css Problem Overview


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 select the last 3 children without knowing how many child elements there could be.

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

For this:

<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> 

I need something like this:

#something a:last-child{
   /* only now it selects the last <a> and the 2 <a>'s that come before*/ 
}

Css Solutions


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

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

Solution 2 - Css

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).

Solution 3 - Css

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...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIvoView Question on Stackoverflow
Solution 1 - CssBassam MehanniView Answer on Stackoverflow
Solution 2 - CsspraseodymView Answer on Stackoverflow
Solution 3 - CssRichard BuffView Answer on Stackoverflow