Is it possible to select the last n items with nth-child?

前端 未结 5 2228
猫巷女王i
猫巷女王i 2020-12-02 09:04

Using a standard list, I\'m trying to select the last 2 list items. I\'ve various permutations of An+B but nothing seems to select the last 2:

l         


        
相关标签:
5条回答
  • 2020-12-02 09:19

    Because of the definition of the semantics of nth-child, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit - thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child gives you.

    0 讨论(0)
  • 2020-12-02 09:27

    If you are using jQuery in your project, or are willing to include it you can call nth-last-child through its selector API (this is this simulated it will cross browser). Here is a link to an nth-last-child plugin. If you took this method of targeting the elements you were interested in:

    $('ul li:nth-last-child(1)').addClass('last');
    

    And then style again the last class instead of the nth-child or nth-last-child pseudo selectors, you will have a much more consistent cross browser experience.

    0 讨论(0)
  • 2020-12-02 09:29

    nth-last-child sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.

    0 讨论(0)
  • 2020-12-02 09:37

    This will select the last two iems of a list:

    li:nth-last-child(-n+2) {color:red;}
    <ul>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
      <li>fred</li>
    </ul>

    0 讨论(0)
  • 2020-12-02 09:44

    :nth-last-child(-n+2) should do the trick

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