CSS :nth-child: what it is, how it works, and examples using odd, even, and An+B formulas

- Andrés Cruz - ES En español

CSS :nth-child: what it is, how it works, and examples using odd, even, and An+B formulas

The :nth-child() pseudo-class in CSS lets you select elements within a list of siblings, whether consecutive or not. To determine which elements match, it uses a mathematical formula based on the element's actual position inside its parent.

For example, :nth-child(2n) selects the second, fourth, sixth child, and so on. You can also combine numbers with an additional formula to target specific elements, such as :nth-child(4n+1), which selects the first element and then every fourth one after that.

The :nth-child() pseudo-class can be applied to any element type in the DOM: containers (div), lists (ul, ol), paragraphs (p), table rows (tr), and so on. You only need to define the value of n. Next, we will look at a series of practical examples to see how it really works.

:nth-child() is one of those CSS tools that seem simple… until you start mixing tags, complex structures, and formulas. In this guide, I explain how it works, how to avoid the most common mistakes, and how to apply it in real-world layout work.

I also include my own experiences: more than once I got a surprise applying an :nth-child() rule that "should work" and did not because of the HTML.

What the :nth-child Pseudo-Class Is and What It Is For

The :nth-child() pseudo-class selects an element based on its actual position within its parent element. It does not take tag type into account (that is what :nth-of-type() is for). It only cares about the spot it occupies among its siblings: first, second, third, and so on.

When I tried it for the first time on a <ul> list, I realized how powerful it is: I could highlight the first <li>, the third, the fifth… without writing selectors one by one.

How Actual Sibling Counting Works in the DOM

Counting always starts at 1, not 0. And here is the key detail that trips up many people:

  • It counts all sibling elements, without exception.
  • It does not matter whether they are <p>, <li>, <div>, or <em>.
  • If the third child is a <span> but your selector is li:nth-child(3), it will not select anything because the third child is NOT an <li>.

Put another way: :nth-child() first counts the position of all children and then checks whether the element at that position matches the selector type you specified.

For example, given this HTML:

<div>
  <span>1</span>
  <span>2</span>
  <em>3</em>
  <span>4</span>
</div>

If you apply:

span:nth-child(3)

It selects nothing, because child number 3 is an <em>, not a <span>.

In my tests with mixed HTML, this is usually the most frequent error and the hardest to spot at a glance.

Key Difference: :nth-child vs :nth-of-type

  • :nth-child(n) → counts all children, regardless of type.
  • :nth-of-type(n) → counts only children of the specified tag type.

If your HTML has mixed tags, :nth-of-type() usually gives more predictable results and fewer headaches.

An example where everyone gets confused:

span:nth-child(2n+1)

If there is an <em> in the middle, counting still includes that <em> even though it is not selected, shifting the pattern relative to what you would expect.

:nth-child() Syntax Explained Step by Step

Exact number

:nth-child(4)

Selects the fourth child, plain and simple. Useful for highlighting specific items in short lists, such as emphasizing the first and third without writing extra classes.

Odd and Even: Odd and Even Without Formulas

The most convenient keywords for :nth-child():

:nth-child(odd)   /* 1, 3, 5, 7... */
:nth-child(even)  /* 2, 4, 6, 8... */

They are ideal for alternating styles without thinking about formulas. odd is equivalent to 2n+1 and even is equivalent to 2n, in case you want to mix them with the general formula.

I use them constantly for tables and long lists where I need to improve readability at a glance.

Painless An+B Formula

The An+B formula is the heart of :nth-child() and lets you create repeating patterns very flexibly:

  • A: the repetition interval.
  • n: a counter that starts at 0 and increments by one (0, 1, 2, 3…).
  • B: the initial shift or offset.

The browser evaluates the formula for each value of n (0, 1, 2, 3…) and selects the children whose index matches the result.

Useful Formulas List

  • 2n → even elements (2, 4, 6…)
  • 2n+1 → odd elements (1, 3, 5…)
  • 3n → every 3 elements (3, 6, 9…)
  • 3n+4 → every 3 elements starting at 4 (4, 7, 10…)
  • -n+3 → only the first 3 elements (3, 2, 1)

The :nth-child Pseudo-Class in CSS to Select Two Specific Elements

For the following list:

<ul class="nth_numerica">
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
  <li>Fourth</li>
  <li>Fifth</li>
  <li>Sixth</li>
  <li>Seventh</li>
</ul>

We will apply the following CSS rule using :nth-child() to change the background color to dark gray on the first and third items:

ul.nth_numerica li:nth-child(1),
ul.nth_numerica li:nth-child(3) {
    background: #999;
}

Applying the rule above gives the following result:

  • First
  • Second
  • Third
  • Fourth
  • Fifth
  • Sixth
  • Seventh

What Happened Exactly?

We simply assigned numeric values to n to specify the positions of the elements we want to select: :nth-child(1) targets the first child and :nth-child(3) targets the third. The CSS rule applied to both independently by separating the selectors with a comma.

The :nth-child Pseudo-Class in CSS to Select Odd Elements

What if you want something more general? That is, applying certain styles to all odd elements (1, 3, 5, 7… n) without selecting them one by one.

For the following list:

<ul class="nth_formula">
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
  <li>Fourth</li>
  <li>Fifth</li>
  <li>Sixth</li>
  <li>Seventh</li>
  <li>Eighth</li>
  <li>Ninth</li>
  <li>Tenth</li>
  <li>Eleventh</li>
  <li>Twelfth</li>
  <li>Thirteenth</li>
  <li>Fifteenth</li>
  <li>Sixteenth</li>
  <li>Seventeenth</li>
</ul>

We apply the following CSS rule:

ul.nth_formula li:nth-child(2n+1) {
    background: #999;
}

As a result, we get:

  • First
  • Second
  • Third
  • Fourth
  • Fifth
  • Sixth
  • Seventh
  • Eighth
  • Ninth
  • Tenth
  • Eleventh
  • Twelfth
  • Thirteenth
  • Fifteenth
  • Sixteenth
  • Seventeenth

What Happened Here?

The 2n+1 formula (where A=2 and B=1) generates indices 1, 3, 5, 7… by substituting n with 0, 1, 2, 3…. This sequence is conceptually equivalent to a loop in programming:

for(i = k; i < n; i += x) {}

Where k is the starting offset (B) and x is the step (A). The loop analogy helps visualize why 2n+1 selects the odd items specifically.

The :nth-child Pseudo-Class in CSS and the odd and even Values

Let's look at a more interesting example that is widely used day to day: alternating background colors on table rows. For the following structure:

<table class="alternar">
    <tr>
        <td>Cell 1 1</td>
        <td>Cell 1 2</td>
    </tr>
    <tr>
        <td>Cell 2 1</td>
        <td>Cell 2 2</td>
    </tr>
    <tr>
        <td>Cell 3 1</td>
        <td>Cell 3 2</td>
    </tr>
</table>

We apply the following rules:

table.alternar tr:nth-child(odd)  { background: #999; }
table.alternar tr:nth-child(even) { background: #CCC; }

The odd and even keywords tell the browser which rows to apply each rule to: odd rows (odd) get the #999 background and even rows (even) get the #CCC background.

The result is as follows:

Cell 1 1 Cell 1 2
Cell 2 1 Cell 2 2
Cell 3 1 Cell 3 2

This alternating row pattern (zebra striping) is one of the simplest and most effective usability tricks for improving data table readability, and with :nth-child() you achieve it in two lines of CSS.

Additional :nth-child Examples in Real-World Cases

Alternating colors in lists

ul li:nth-child(odd) {
    background: #f5f5f5;
}
ul li:nth-child(even) {
    background: #e1e1e1;
}

When I tried this for the first time, I realized I did not need :first-child or manual classes. With just odd and even, the list looks visually clean.

Alternating Table Rows

The classic example adapted to any table:

table tr:nth-child(odd)  { background: #999; }
table tr:nth-child(even) { background: #CCC; }

It remains one of the most direct ways to improve tabular data readability without touching the HTML.

Selecting only some elements in grids or cards

.card:nth-child(3n) {
    transform: scale(1.05);
}

Every third card will receive a different style. Useful when you need to break up monotony in repetitive layouts or visually highlight elements at regular intervals.

How mixing tags affects selection

If your HTML has this structure:

<li>1</li>
<li>2</li>
<div>OPS</div>
<li>3</li>

Then the selector:

li:nth-child(3)

DOES NOT select the third <li>. The browser evaluates it like this:

  • → "Is the parent's third child an <li>?"
  • → No. It is a <div>.
  • → Result: selects nothing.

Modern Usage: :nth-child(A of selector)

One of the most interesting and lesser-known additions in modern CSS is the extended :nth-child() syntax:

:nth-child(2 of .item)

This variant selects the second element that has the .item class even when other elements of different types are in between. It is much more predictable than classic behavior when HTML is not homogeneous. It currently has good support in modern Safari and Chromium, though Firefox support is more recent.

There is also the companion :nth-last-child(), which counts from the end:

:nth-last-child(1)
/* equivalent to the last child */

Very useful when working with dynamically generated structures and you do not know in advance how many children there will be.

Common :nth-child Mistakes and How to Avoid Them

When :nth-child does not select what you expect

Most common causes:

  • There are invisible elements in the DOM (<script>, <template>) that get counted as children.
  • Different tags are mixed unintentionally inside the same container.
  • The An+B pattern does not start at the position you think because of the offset.

Typical Mistakes with Messy Real-World HTML

If you inherit HTML where someone mixed <p>, <div>, and <span> without order, your :nth-child() pattern will be unpredictable. Solutions:

  • Use :nth-of-type() to count only the tag type you care about.
  • Clean up the HTML so all children are of the same type.
  • Apply the new :nth-child(n of .class) syntax available in modern browsers.

Quick summary

  • To highlight specific items I use :nth-child(1), :nth-child(3)…: direct and straightforward.
  • For odd items I reach for 2n+1: it is the clearest way to see how the pattern advances.
  • For tables, odd and even remain my favorite combination: alternating backgrounds greatly improves readability at a glance.

Selecting Ranges of Elements with :nth-child in CSS

Selecting ranges of elements with CSS using nth-child

When working with lists (<ul>) where the user can select a range of items, visually marking that selected region is almost mandatory. You can do it simply and efficiently with CSS by chaining multiple :nth-child() pseudo-classes in the same rule.

The :nth-child Selector to the Rescue for Range Selection

We have already seen how the :nth-child() selector works. Its real power for ranges shows up when you chain two instances of the same selector on the same element, acting as a compound filter:

To select a range of elements, simply chain the :nth-child selector twice in the same rule:
ul li:nth-child(n+5):nth-child(-n+15) {
    background: #08B;
}

With this rule, we get the selection from item 5 to 15:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

How Does This Range CSS Work?

The key is understanding each part separately. First, :nth-child(n+5) selects all elements starting from the fifth (5 through 20):

ul li:nth-child(n+5) {
    background: #08B;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Then, :nth-child(-n+15) acts as a second filter over that already-selected group, limiting the selection up to item 15 (1 through 15). Combining both—:nth-child(n+5):nth-child(-n+15)—produces the intersection: items 5 through 15. This chained-range technique is simple, efficient, and works in all modern browsers without needing JavaScript.

Frequently Asked Questions About :nth-child in CSS

  • What does :nth-child() actually select?
    • The Nth child within a parent, counting from 1 and counting every single tag type present.
  • Are :nth-child() and :nth-of-type() the same?
    • No. :nth-child() counts all siblings; :nth-of-type() counts only those of the same tag type.
  • Why isn't my :nth-child() working?
    • Because the element's actual position in the DOM does not match the tag type you are selecting. Check the HTML with your browser's DevTools.
  • What does the An+B formula mean?
    • A pattern that repeats every A elements, shifted by B positions from the start.
  • What happens if I mix tags inside the same container?
    • Your pattern can break because counting includes all children. Use :nth-of-type(), clean up the HTML, or apply the modern :nth-child(n of .class) syntax.
  • How do I select the second child in CSS?
    • With :nth-child(2). If you want the second element of a specific type, use :nth-of-type(2) to avoid issues with mixed tags.
  • Can I use :nth-child() with document.querySelector() in JavaScript?
    • Yes. For example: document.querySelector("#tabla > tbody > tr:nth-child(2)") selects the second row of the tbody. The selector syntax inside querySelector() is identical to CSS.

The next selector worth learning is the CSS :checked pseudo-class, which selects form elements.

Learn how to use the :nth-child pseudo-class in CSS to select elements by their position using numbers, odd, even, and the An+B formula. This guide includes real-world examples—such as lists, tables, and grids—explains the differences between :nth-child and :nth-of-type, shows how to select ranges, and covers how to avoid common mistakes.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.