:nth-child()

The :nth-child()CSSpseudo-class matches one or more elements based on their position among a group of siblings.

/* Selects every fourth element
among any group of siblings */
:nth-child(4n) {
color: lime;
}

Syntax

The nth-child pseudo-class is specified with a single argument, which represents the pattern for matching elements.

Keyword values

odd

Represents elements whose numeric position in a series of siblings is odd: 1, 3, 5, etc.

even

Represents elements whose numeric position in a series of siblings is even: 2, 4, 6, etc.

Functional notation

<An+B>

Represents elements whose numeric position in a series of siblings matches the pattern An+B, for every positive integer or zero value of n. The index of the first element is 1. The values A and B must both be <integer>s.

Represents every <p> element among a group of siblings. This is the same as a simple p selector.

p:nth-child(1) or p:nth-child(0n+1)

Represents every <p> that is the first element among a group of siblings. This is the same as the :first-child selector.

Detailed example

HTML

<h3><code>span:nth-child(2n+1)</code>, WITHOUT an
<code>&lt;em&gt;</code> among the child elements.</h3>
<p>Children 1, 3, 5, and 7 are selected.</p>
<div class="first">
<span>Span 1!</span>
<span>Span 2</span>
<span>Span 3!</span>
<span>Span 4</span>
<span>Span 5!</span>
<span>Span 6</span>
<span>Span 7!</span>
</div>
<br>
<h3><code>span:nth-child(2n+1)</code>, WITH an
<code>&lt;em&gt;</code> among the child elements.</h3>
<p>Children 1, 5, and 7 are selected.<br>
3 is used in the counting because it is a child, but it isn't
selected because it isn't a <code>&lt;span&gt;</code>.</p>
<div class="second">
<span>Span!</span>
<span>Span</span>
<em>This is an `em`.</em>
<span>Span</span>
<span>Span!</span>
<span>Span</span>
<span>Span!</span>
<span>Span</span>
</div>
<br>
<h3><code>span:nth-of-type(2n+1)</code>, WITH an
<code>&lt;em&gt;</code> among the child elements.</h3>
<p>Children 1, 4, 6, and 8 are selected.<br>
3 isn't used in the counting or selected because it is an <code>&lt;em&gt;</code>,
not a <code>&lt;span&gt;</code>, and <code>nth-of-type</code> only selects
children of that type. The <code>&lt;em&gt;</code> is completely skipped
over and ignored.</p>
<div class="third">
<span>Span!</span>
<span>Span</span>
<em>This is an `em`.</em>
<span>Span!</span>
<span>Span</span>
<span>Span!</span>
<span>Span</span>
<span>Span!</span>
</div>