How to use nth-child

Standard

There is a CSS selector, really a pseudo-selector, called nth-child.

This pseudo-class matches elements on the basis of their positions within a parent element’s list of child elements. The pseudo-class accepts an argument, N, which can be a keyword, a number, or a number expression of the form an+b.

This example selector will match any paragraph that’s the first child element of its parent element (This is, of course, equivalent to the selector p:first-child):

p:nth-child(1) {
  /*declarations*/
}

Using a formula (an + b).
Description: a represents a cycle size, n is a counter (starts at 0), and b is an offset value.

If you want to specify a color for all p elements whose index is a multiple of 3:

p:nth-child(3n+0) {
    color: SteelBlue;
}

The following example selectors are equivalent, and will match odd-numbered table rows:

tr:nth-child(2n+1) {
  /*declarations*/
}
tr:nth-child(odd) {
  /*declarations*/
}

Select only the first 2 elements

p:nth-child(-n+2) {
    /*declarations*/
}

Select only the last 2 elements

p:nth-child(n+2) {
    /*declarations*/
}

If you want select elements within certain ranges, for an example, elements 4-8.

li:nth-child(n+4):nth-child(-n+8) {
    /*declarations*/
}