CSS3/Selectors/pseudo-classes/:nth-child

From W3C Wiki
Jump to: navigation, search

Pseudo-class :nth-child()

The :nth-child() pseudo-class represents an element that has an+b siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

Syntax

selector:nth-child(an+b){ properties }


Point, Note

  • The examples of an+b are as follows:
    •  :nth-child(2n) /* represents every even element */
    •  :nth-child(even) /* same, represents every even element */
    •  :nth-child(2n+1) /* represents every odd element */
    •  :nth-child(odd) /* same, represents every odd element */
    •  :nth-child(10n-1) /* represents the 9th, 19th, 29th, etc, element */


Example

[style.css]

 tr:nth-child(2n){
   background-color: yellow;
 }


[index.html]

<body>
  <table>
    <tr><td>This is first row.</td></tr>
    <tr><td>This is second row.</td></tr>
    <tr><td>This is third row.</td></tr>
    <tr><td>This is fourth row.</td></tr>
  </table>
</body>

Css3 selectors nth-child.png

The CSS Selectors Level 3 specification defines the :nth-child() pseudo-class selector in 6.6.5.2. :nth-child() pseudo-class.