{"id":14232,"date":"2011-09-06T20:20:33","date_gmt":"2011-09-07T03:20:33","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=14232"},"modified":"2013-04-03T05:39:46","modified_gmt":"2013-04-03T12:39:46","slug":"nth-last-child","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/selectors\/n\/nth-last-child\/","title":{"rendered":":nth-last-child"},"content":{"rendered":"

The :nth-last-child<\/code> selector allows you select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec<\/a> as a \u201cstructural pseudo-class\u201d, meaning it is used to style content based on its relationship with parent and sibling elements. It functions the same as :nth-child<\/code><\/a> except it selects items starting at the bottom of the source order, not the top.<\/p>\n

Suppose we have a list with an unknown number of items, and we wish to highlight the second-to-last item (in this exact example, the “Fourth Item”):<\/p>\n

<ul>\r\n  <li>First Item<\/li>\r\n  <li>Second Item<\/li>\r\n  <li>Third Item<\/li>\r\n  <li>Fourth Item<\/li>\r\n  <li>Fifth Item<\/li>\r\n<\/ul><\/code><\/pre>\n

Rather than doing something like adding a class to the list item (e.g. .highlight<\/code>) we can use :nth-last-child<\/code>:<\/p>\n

li {\r\n  background: slategrey;\r\n}\r\n\/* select the second-last item *\/\r\nli:nth-last-child(2) {\r\n  background: lightslategrey;\r\n}<\/code><\/pre>\n

As you can see, :nth-last-child<\/code> takes an argument: this can be a single integer, the keywords \u201ceven\u201d or \u201codd\u201d, or a formula. If an integer is specified only one element is selected \u2013 but the keywords or a formula will iterate through all the children of the parent element and select matching elements\u2014similar to navigating items in an array in JavaScript. Keywords \u201ceven\u201d and \u201codd\u201d are straightforward (2, 4, 6 etc or 1, 3, 5 respectively). The formula is constructed using the syntax an+b<\/code>, where:<\/p>\n