日本語

Why CSS :nth-child Styles the Wrong Element (and How to Fix It)

​​CSS​HTML,Playwright

:nth-child() counts an element's position among its siblings, the elements that share the same parent. Counting starts at 1. When a color lands on the wrong element, the siblings being counted may not be the ones you expect. This article covers why colors shift, appear on every item, or appear on none when you try to color every other list item or card, or highlight the first three items, and how to fix each case.

Note

Test environment: Ubuntu 24.04, Node.js 22.23.5, Playwright 1.63.0, Chromium 158. I opened a page with only HTML and CSS in Playwright, checked the matched elements with document.querySelectorAll(), and checked the colors that were actually applied with getComputedStyle(). I did not test Firefox or Safari.

Formulas match the numbers you get by plugging 0, 1, 2… into n

First, I checked which elements each formula matches. I used a list of ten li elements and recorded the li elements that matched each formula.

A table with seven rows. On the left are :nth-child formulas. On the right are boxes numbered 1 to 10, and the matched boxes are shaded light blue. odd matches 1, 3, 5, 7, and 9. even matches 2, 4, 6, 8, and 10. 3n matches 3, 6, and 9. 3n+1 matches 1, 4, 7, and 10. n+3 matches 3 through 10. -n+3 matches 1 through 3. 0 matches nothing.
Background colors applied to ten li elements using :nth-child, one formula per row
Formula Matched li elements
odd, 2n+1 1, 3, 5, 7, 9
even, 2n 2, 4, 6, 8, 10
3n 3, 6, 9
3n+1 1, 4, 7, 10
n+3 3 through 10
-n+3 1, 2, 3
0 None
n 1 through 10 (all)

The browser plugs 0, 1, 2… into n in order, and each result is a position number that matches the element at that position. As MDN's :nth-child() reference describes, positions start at 1. :nth-child(0) matched no elements. If you are used to zero-based arrays and write 0 for the first item, nothing gets selected.

"From the third item onward" is n+3, and "the first three items" is -n+3. If you mix these up, the colored items flip to the other side of the third item.

If each element is wrapped separately, every one is the first child

I had a card layout where each .card was wrapped in its own <div class="wrap">. Using .card:nth-child(even) matched no cards.

html
<div class="cards">
  <div class="wrap"><div class="card">カード1</div></div>
  <div class="wrap"><div class="card">カード2</div></div>
  <div class="wrap"><div class="card">カード3</div></div>
  <div class="wrap"><div class="card">カード4</div></div>
</div>

Each .card has a different parent .wrap, and each card is the first child of its parent. So changing the selector to .card:nth-child(odd) colored all four cards. The same thing happens when each item is wrapped in its own <a> for a link, or in an outer <div> for a component.

To fix this, count the outer elements, which are siblings in the list.

css
.wrap:nth-child(even) .card {
  color: #d85878;
}

With this CSS, the second and fourth cards were colored.

Hidden elements also count as siblings

Elements that are not visible on the page still count. I tested a form that starts with <input type="hidden">, followed by four .field elements.

html
<form>
  <input type="hidden" name="token" value="x">
  <div class="field">名前</div>
  <div class="field">メール</div>
  <div class="field">電話</div>
  <div class="field">住所</div>
</form>
Three forms stacked vertically. In the top form, .field:nth-child(odd) puts a light blue band on "Email" and "Address". In the middle form, .field:nth-of-type(odd) puts the band on "Name" and "Phone". In the bottom form, .field:nth-child(odd of .field) also puts the band on "Name" and "Phone". The field labels are in Japanese: name, email, phone, and address.
Three selectors used to color every other field in a form that has a hidden input at the start

.field:nth-child(odd) matched "Email" and "Address", not "Name" and "Phone". The input has display: none and is not visible, but it still counts as the first child, so "Name" becomes the second child. The HTML Standard's default styles for hidden elements set input[type=hidden] to display: none. A <template> behaves the same way. When I placed one at the start of a <ul>, li:nth-child(odd) matched the second and fourth items.

To count only .field elements, use this:

css
/* Count only .field */
.field:nth-child(odd of .field) {
  background: #eefafd;
}

:nth-child(odd of .field) counts only the siblings that match .field, so it matched "Name" and "Phone". .field:nth-of-type(odd) gave the same result. It counts only siblings with the same element name, so it matches the first and third div elements. In this example the hidden element was an input and the fields were div elements, so both selectors gave the same result.

When I put text and a comment at the start of a <ul>, li:nth-child(odd) matched the first and third items. Text and comments are not counted.

When you use an element name, such as li:nth-child(2), the count still includes all siblings, whatever their element names. I covered this difference in another article, "The Difference Between :first-child and :first-of-type in CSS." If hiding a row with the hidden attribute or display: none shifts the stripes in a table, I tested that in another article, "How to Color Every Other Table Row with CSS."

Some spaces in the formula make the whole rule ignored

The places where you can put spaces in a formula are limited. I used CSS.supports() to check which forms are accepted as selectors.

Written as Result
2n+1, 2n + 1, 2n+ 1, 2n +1 Valid
2 n+1 (space between 2 and n) Invalid
-n+3 Valid
- n+3 (space between - and n) Invalid
+2n Valid
+ 2n (space between + and 2n) Invalid
ODD, 2N+1 (uppercase) Valid

The An+B microsyntax section of CSS Syntax Level 3 allows spaces inside the formula only around the + or - that separates An and B. You cannot put a space inside a token such as 2n or -n. Adding a space just inside the parentheses, as in ( 2n+1 ), was valid in my tests.

An invalid selector causes its rule to be discarded. This is a problem when only one of several comma-separated selectors is invalid:

css
li:nth-child(1), li:nth-child(2 n) {
  color: #d85878;
}

With this CSS, even the valid li:nth-child(1) was not colored. When I read the rules with document.styleSheets, there were no rules left. As MDN's selector list reference explains, if any selector in a selector list is invalid, the entire rule is ignored.

When I split the selectors into two rules, the first li was colored. Wrapping them in :is(), as in :is(li:nth-child(1), li:nth-child(2 n)), also colored the first li. Inside :is(), only the invalid selector is ignored.

The element is selected, but the link inside keeps its color

Even when the li is selected, the text inside an <a> does not take the color.

html
<ul class="menu">
  <li><a href="#1">メニュー1</a></li>
  <li><a href="#2">メニュー2</a></li>
  <li><a href="#3">メニュー3</a></li>
</ul>

With .menu li:nth-child(2) { color: #d85878; }, the color of the second li was rgb(216, 88, 120). The a inside it stayed at rgb(0, 0, 238). The HTML Standard's default styles include :link { color: #0000EE; }, so links use this color instead of inheriting the parent's color.

Color the a inside the li that :nth-child() selects:

css
.menu li:nth-child(2) a {
  color: #d85878;
}

With this CSS, only the link in the second item became rgb(216, 88, 120). To tell whether the problem is the selector or the link color, read the color of both the li and the a with getComputedStyle(). If the li value changed, :nth-child() is selecting it correctly.

Even when the visual order is reversed, counting follows the HTML order

I used display: flex and flex-direction: row-reverse to display four li elements from right to left. li:nth-child(1) colored the first li in the HTML, which was the rightmost item on the screen. The left edges of the items were at x = 328px for the first item and x = 88px for the fourth.

Even with row-reverse reversing the visual order, the :nth-child() numbers still followed the HTML order.

To select the element at the left edge of the screen, which is the last item in the HTML, use :nth-last-child(), which counts from the end. li:nth-last-child(1) colored the fourth li, which was on the left of the screen. I covered changing the visual order with order in another article, "How to Swap the Display Order on Mobile and Desktop with CSS order."

​Posted by 86