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

CssCss Selectors

Css Problem Overview


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:

li:nth-child(n+2) {} /* selects from the second onwards */
li:nth-child(n-2) {} /* selects everything */
li:nth-child(-n+2) {} /* selects first two only */
li:nth-child(-n-2) {} /* selects nothing */

I'm aware of a new CSS3 selectors like :nth-last-child() but I'd prefer something that works in a few more browsers if possible (don't care about IE particularly).

Css Solutions


Solution 1 - Css

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

Solution 2 - Css

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.

Solution 3 - Css

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

Solution 4 - Css

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.

Solution 5 - Css

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.

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
QuestionDisgruntledGoatView Question on Stackoverflow
Solution 1 - CssJohn GuiseView Answer on Stackoverflow
Solution 2 - CssPekkaView Answer on Stackoverflow
Solution 3 - CssDanyl SobolevView Answer on Stackoverflow
Solution 4 - CssPointyView Answer on Stackoverflow
Solution 5 - CssNathan AndersonView Answer on Stackoverflow