Grow your CSS skills. Land your dream job.

nth-last-child(???)

  • # December 4, 2012 at 10:19 am

    I have a peculiar want. The last three children in an li. I wish to target them only. Is it possible to do so?

    I guess I could do them individually like so:

    li:last-child,
    li:nth-last-child(2),
    li:nth-last-child(3) {
    margin-bottom: 0;
    }

    but I would rather not, is there a way around this?

    # December 4, 2012 at 10:41 am

    Nope…the code you gave is the way to go unless you add a specific class or use JS

    # December 4, 2012 at 10:54 am

    Thought as much, kinda sucks you can’t select up to a point really. What if I needed to get up to 100? I know it’s unlikely, but still. Oh well.

    Thank you. =]

    # December 4, 2012 at 11:06 am

    http://codepen.io/JamyGolden/pen/qfBFE

    # December 4, 2012 at 11:11 am

    I was about to go the same route: giving all elements a certain style (the one you want for the last X element) and then use another style on top of that, EXCLUDING the last three.

    # December 4, 2012 at 11:12 am

    Damn…that works…tried it a different way and couldn’t get it.

    # December 4, 2012 at 4:59 pm

    @jamy_za’s solution works great. Another tip, if you wanted to specifically target the last three (instead of everything but the last three), you can use this:

    :nth-last-child(-n + 3)
    # December 5, 2012 at 6:22 am

    @joshuanhibbert THAT’s what I was trying to figure out. I KNEW there was a ‘minus’ in there somewhere.

    Bingo!

    # December 11, 2012 at 3:48 am

    Well this is certainly solved. Thank you everyone. CSS is a sly fox sometimes. You would expect the minus symbol to be before the number.

Viewing 9 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".