Is it possible? If not, is there a way to do it with jQuery?
:last-child,
:nth-last-child(2) {
ruleset
}
will play as well.
For me it was this:
li:not(:nth-last-child(-n+2))
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/
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