Instance
Specifies the background color of each p that belongs to the second child element of its parent element:
p:nth-child(2)
{background: #ff0000;}
Try it yourself.
Browser support
IE |
Firefox |
Chrome |
Safari |
Opera |
|
|
|
|
|
All major browsers support: Nth-child () selector, except for IE8 and earlier versions.
Definition and usage
: The Nth-child (n) selector matches the nth child element that belongs to its parent element, regardless of the type of the element.
n can be a number, a keyword, or a formula.
Tip: See: Nth-of-type () selector, which selects child elements of the nth specified type of a parent element.
Try it yourself-instance instance 1
ODD and even are keywords that can be used to match sub-elements with an odd or even number subscript (the subscript for the first child element is 1).
Here, we specify two different background colors for the odd and even p elements:
p:nth-child(odd)
{background: #ff0000;} p:nth-child(even)
{background: #0000ff;}
Try it yourself.
Example 2
Use the formula (an + b). Description: Indicates the length of the period, N is the counter (starting at 0), and B is the offset value.
Here, we specify the background color of all p elements that have a multiple of 3 in the subscript:
p:nth-child(3n+0)
{background: #ff0000;}
Css3:nth-child () Selector