How do I choose the last 2 items in a list with css nth-child?

后端 未结 4 551
不知归路
不知归路 2021-01-31 08:29

Is it possible? If not, is there a way to do it with jQuery?

相关标签:
4条回答
  • 2021-01-31 09:01
    :last-child,
    :nth-last-child(2) {
      ruleset
    }
    

    will play as well.

    0 讨论(0)
  • 2021-01-31 09:07

    For me it was this: li:not(:nth-last-child(-n+2))

    0 讨论(0)
  • 2021-01-31 09:15

    Unfortunately it's impossible.. Disregard this answer and look at spliters answer below.

    If it were to be possible, it would look something like...

    ul li:last-child+li {...}
    

    But this doesn't work, because + will select the immediate sibling after last-child (which is nothing, of course). There is no immediate previous selector.

    There are different ways of achieving this with jQuery, the most performant would be...

    var lastItems = $("#list li");
    lastItems.slice(lastItems.length - 2).addClass("whatever");
    

    http://jsfiddle.net/qkzdJ/

    0 讨论(0)
  • 2021-01-31 09:21

    It is possible with CSS3. Consider the markup:

    <ul>
        <li><a href="">First item</a></li>
        <li>Second item</li>
        <li><a href="">Test</a></li>
        <li><a href="">Test</a></li>
        <li><a href="">Pre-last item</a></li>
        <li><a href="">Last item</a></li>
    </ul>
    

    To choose the last two LI elements you do:

    ul > li:nth-last-of-type(-n+2) {
        background: green;
    }
    

    Works in all contemporary browsers including IE9, but excluding IE8 and below. To add support for those browsers, you might consider using Selectivizr.js

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