CSS nth-last-child(n) Selector :nth-last-child(n)

What is CSS :nth-last-child(n) Selector?

CSS :nth-last-child(n) selector matches only nth last child element of an parent element.

Syntax

General syntax of :nth-last-child selector,

:nth-last-child(n) {
  property: value;
  property: value;
  ...
}

/* nth number item in list from last */
li:nth-last-child(n) {
  property: value;
  property: value;
  ...
}

/* select odd item in list from last */
li:nth-last-child(odd) {
  property: value;
  property: value;
  ...
}

/* select even item in list from last */
li:nth-child(even) {
  property: value;
  property: value;
  ...
}

/* every second item in list from last*/
li:nth-child(2n+1) {
  property: value;
  property: value;
  ...
}

/* every third item in list from last*/
li:nth-child(3n+1) {
  property: value;
  property: value;
  ...
}

Example

CSS li:nth-last-child(2) selector select only second last <li> element whose are child of an <ul> element.

<!DOCTYPE html>
<html>
<head>
  <title>CSS :nth-last-child(n) Selector</title>
  <style type="text/css">
    li:nth-last-child(2) {
      background:#ff0000;
    }
  </style>
</head>
<body>
  <ul>
    <li>first item</li>
    <li>second item</li>
    <li>third item</li>
    <li>forth item</li>
    <li>fifth item</li>
  </ul>
</body>
</html>

Run it...   »

Example

CSS li:nth-child(3n+1) selector select every third <li> element from last and whose are child of an <ul> element.

<!DOCTYPE html>
<html>
<head>
  <title>CSS :nth-last-child(n) Selector</title>
  <style type="text/css">
    li:nth-last-child(3n+1) {
      background:#ff0000;
    }
  </style>
</head>
<body>
  <ul>
    <li>first item</li>
    <li>second item</li>
    <li>third item</li>
    <li>forth item</li>
    <li>fifth item</li>
  </ul>
</body>
</html>

Run it...   »

Browser Compatibility

  • Google Chrome 2+
  • Mozilla Firefox 3+
  • Internet Explorer 9+
  • Opera 9.5+
  • Safari 4+

Note: Here details of browser compatibility with version number may be this is bug and not supported. But recommended to always use latest Web browser.