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

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

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

Syntax

General syntax of CSS :nth-child selector,

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

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

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

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

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

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

Example

CSS li:nth-child(2) selector select only second <li> element of its <ul> parent element.

<!DOCTYPE html>
<html>
<head>
  <title>CSS :nth-child(n) Selector</title>
  <style type="text/css">
    li:nth-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...   »

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.