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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)