The :Nth-Child(n) Pseudo-Class

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. The 'n' can be a number, a keyword, or a formula. In this example, the selector specifies a background color for every <p> element that is the second child of its parent:

HTML file: Displayed by browser:

<style>
p:nth-child(2) {
    background: #ff0000;
}
</style>


<body>
<h1>This is a heading.</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</body>

This is a heading

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

The heading is the first child of the parent (body) element, while the highlighted paragraph is the second child. Use the :nth-of-type() selector to select the element that is the nth child, of a particular type, of its parent. Note: Internet Explorer 8 and earlier versions do not support the :nth-child() selector.

Back button Table of Contents Next button