Bird
Raised Fist0
CSSmarkup~15 mins

Nth-child selector in CSS - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Nth-child selector
What is it?
The nth-child selector in CSS lets you pick elements based on their position among siblings. You write a pattern like '2n' or '3n+1' to select every 2nd or 3rd element, for example. It helps style items in lists, tables, or groups without adding extra classes. This selector works by counting elements from the start inside their parent container.
Why it matters
Without nth-child, styling repeated patterns in lists or grids would need extra HTML classes or manual styling. This selector saves time and keeps HTML clean by letting CSS handle patterns. It makes designs flexible and easier to update, especially for things like zebra stripes or alternating colors. Without it, web pages would be harder to maintain and less dynamic.
Where it fits
Before learning nth-child, you should know basic CSS selectors like element, class, and id selectors. After mastering nth-child, you can explore related selectors like nth-of-type and advanced CSS layout techniques like Flexbox and Grid. This fits into the journey of mastering CSS selectors and styling patterns.
Mental Model
Core Idea
Nth-child selects elements by counting their position among siblings using a simple math formula.
Think of it like...
Imagine a row of chairs numbered from left to right. Nth-child is like choosing every 2nd or 3rd chair to decorate without touching the others.
Parent container
│
├─ Element 1
├─ Element 2 ← selected if nth-child(2)
├─ Element 3
├─ Element 4 ← selected if nth-child(2n)
├─ Element 5
└─ Element 6 ← selected if nth-child(2n)
Build-Up - 7 Steps
1
FoundationBasic nth-child syntax and usage
🤔
Concept: Learn the simple syntax and how nth-child counts elements.
The nth-child selector uses a formula inside parentheses to pick elements by position. For example, 'li:nth-child(2)' selects the second list item. The formula can be a number or a pattern like '2n' which means every 2nd element. Example: ul li:nth-child(2) { color: red; } This colors the second list item red.
Result
Only the second list item in the list turns red.
Understanding that nth-child counts elements starting at 1 helps you target specific positions without extra classes.
2
FoundationCounting starts at one, not zero
🤔
Concept: Nth-child counts elements starting from 1, not zero like some programming languages.
When you write nth-child(1), it selects the very first child. Counting always starts at 1, so nth-child(0) does not select anything. Example: li:nth-child(1) { font-weight: bold; } This makes the first list item bold.
Result
The first list item is bold, no zero-based counting confusion.
Knowing counting starts at 1 prevents off-by-one errors when selecting elements.
3
IntermediateUsing formulas like an+b
🤔Before reading on: do you think '2n+1' selects even or odd elements? Commit to your answer.
Concept: Nth-child accepts formulas like 'an+b' to select repeating patterns of elements.
The formula 'an+b' means start at element b, then select every a-th element after. Examples: - nth-child(2n) selects every even element (2,4,6,...) - nth-child(2n+1) selects every odd element (1,3,5,...) - nth-child(3n+1) selects elements 1,4,7,10... This lets you style stripes or patterns easily.
Result
Elements matching the formula get styled, creating repeating patterns.
Understanding the formula lets you create complex repeating styles without extra markup.
4
IntermediateNegative and zero values in formulas
🤔Before reading on: does nth-child(-n+3) select the first three or last three elements? Commit to your answer.
Concept: You can use negative and zero values in formulas to select elements from the start or a limited range.
The formula '-n+3' selects elements where the position is less than or equal to 3. Example: ul li:nth-child(-n+3) { background: yellow; } This highlights the first three list items. Zero (0) in formulas means no offset, so nth-child(3n+0) is the same as nth-child(3n).
Result
The first three elements get highlighted with yellow background.
Knowing how negative values work lets you select ranges easily, not just repeating patterns.
5
IntermediateDifference between nth-child and nth-of-type
🤔Before reading on: do you think nth-child and nth-of-type select the same elements in mixed content? Commit to your answer.
Concept: Nth-child counts all element types, nth-of-type counts only elements of the same type.
If a parent has mixed elements like
  • and

    , nth-child counts all children regardless of type. Example: ul > *:nth-child(2) selects the second child no matter its tag. But ul li:nth-of-type(2) selects the second

  • only, ignoring other tags. This matters when you want to style only certain tags in a mixed list.
  • Result
    Nth-child and nth-of-type select different elements when siblings have mixed tags.
    Knowing this difference prevents styling the wrong elements in mixed content.
    6
    AdvancedCombining nth-child with other selectors
    🤔Before reading on: can you combine nth-child with classes or pseudo-classes? Commit to your answer.
    Concept: Nth-child can be combined with classes, attributes, and pseudo-classes for precise styling.
    You can write selectors like: ul li:nth-child(odd).highlight { color: blue; } This selects odd list items that also have the class 'highlight'. You can also combine with :not(), :first-child, or attribute selectors for complex rules. Example: ul li:nth-child(3n):not(.skip) { background: lightgray; }
    Result
    Only every 3rd list item without the 'skip' class gets a light gray background.
    Combining selectors lets you target very specific elements, making CSS powerful and flexible.
    7
    ExpertPerformance and browser quirks of nth-child
    🤔Before reading on: do you think nth-child selectors slow down page rendering significantly? Commit to your answer.
    Concept: Nth-child selectors are efficient but can have quirks in older browsers and affect rendering if overused.
    Modern browsers optimize nth-child well, so performance impact is minimal for normal use. However, very complex or deeply nested nth-child selectors can slow rendering. Older browsers had bugs with formulas like 'an+b' or negative values. Also, nth-child counts only element nodes, excluding text and comment nodes, including hidden or script tags, which can cause unexpected results. Testing in target browsers is important.
    Result
    Understanding performance and quirks helps write reliable, fast CSS.
    Knowing browser behavior prevents subtle bugs and performance issues in production.
    Under the Hood
    The browser parses the CSS and, for nth-child selectors, counts the element's position among its siblings in the DOM tree. It applies the formula 'an+b' to the index (starting at 1) to decide if the element matches. This counting happens dynamically during rendering, so changes in the DOM update the selection automatically.
    Why designed this way?
    Nth-child was designed to let CSS target elements by position without extra HTML markup. The formula syntax 'an+b' is a compact way to express repeating patterns and ranges. Alternatives like adding classes for each pattern would be tedious and error-prone. The design balances power and simplicity for styling patterns.
    Parent element
    │
    ├─ Child 1 (index 1)
    ├─ Child 2 (index 2)
    ├─ Child 3 (index 3)
    ├─ Child 4 (index 4)
    └─ Child 5 (index 5)
    
    Selector: nth-child(2n+1)
    Matches: Child 1, Child 3, Child 5
    
    Process:
    Count index → Apply formula → Match or not
    Myth Busters - 4 Common Misconceptions
    Quick: Does nth-child(2n) select odd or even elements? Commit to your answer.
    Common Belief:Nth-child(2n) selects odd elements because it starts counting at 2.
    Tap to reveal reality
    Reality:Nth-child(2n) selects even elements: 2, 4, 6, and so on.
    Why it matters:Misunderstanding this leads to styling the wrong elements, breaking design patterns like zebra stripes.
    Quick: Does nth-child count only elements of the same type? Commit to your answer.
    Common Belief:Nth-child counts only elements of the same tag type.
    Tap to reveal reality
    Reality:Nth-child counts all element siblings regardless of tag type; nth-of-type counts only same tag types.
    Why it matters:Confusing these causes unexpected styling when siblings have mixed tags.
    Quick: Does nth-child(0) select any elements? Commit to your answer.
    Common Belief:Nth-child(0) selects the first element because zero means start.
    Tap to reveal reality
    Reality:Nth-child(0) selects no elements because counting starts at 1 and zero is invalid.
    Why it matters:Using zero causes selectors to fail silently, confusing debugging.
    Quick: Can nth-child select elements based on classes or attributes alone? Commit to your answer.
    Common Belief:Nth-child can select elements by class or attribute without counting position.
    Tap to reveal reality
    Reality:Nth-child only selects by position; classes or attributes require separate selectors combined with nth-child.
    Why it matters:Expecting nth-child to select by class alone leads to ineffective CSS rules.
    Expert Zone
    1
    Nth-child counts all element nodes, including those hidden by CSS or scripts, which can affect selection unexpectedly.
    2
    The formula 'an+b' can use zero or negative values to create flexible ranges, but negative values behave differently than in math, selecting elements up to a position.
    3
    Combining nth-child with pseudo-classes like :not() or attribute selectors allows very precise targeting, but can increase CSS complexity and affect maintainability.
    When NOT to use
    Avoid nth-child when elements are dynamically reordered or inserted frequently, as it can cause unpredictable styling. Instead, use classes or JavaScript to manage styles. Also, for selecting elements by type only, nth-of-type is more appropriate.
    Production Patterns
    Nth-child is widely used for zebra striping tables, alternating list item colors, grid layouts with repeating patterns, and responsive designs where classes are impractical. It is often combined with CSS variables and custom properties for theme flexibility.
    Connections
    Modular Arithmetic
    Nth-child formulas use modular arithmetic to select repeating elements.
    Understanding modular arithmetic helps grasp how 'an+b' cycles through element positions to create patterns.
    Database Row Numbering
    Both nth-child and database row numbering assign positions to items to filter or style them.
    Knowing how databases number rows clarifies how nth-child counts elements in order.
    Music Rhythm Patterns
    Nth-child's repeating selection patterns are like beats in music repeating every few counts.
    Recognizing rhythmic cycles in music helps understand how CSS selects elements in repeating intervals.
    Common Pitfalls
    #1Using nth-child to select elements by class alone.
    Wrong approach:li:nth-child(.highlight) { color: red; }
    Correct approach:li.highlight { color: red; }
    Root cause:Misunderstanding that nth-child selects by position, not by class.
    #2Assuming nth-child counts only visible elements.
    Wrong approach:ul li:nth-child(2) { color: blue; } /* expecting second visible item */
    Correct approach:Use JavaScript or add classes to visible items, because nth-child counts all elements regardless of visibility.
    Root cause:Not realizing nth-child counts all siblings in the DOM, not filtered by CSS visibility.
    #3Using zero or negative numbers incorrectly in formulas.
    Wrong approach:li:nth-child(0) { font-weight: bold; }
    Correct approach:li:nth-child(1) { font-weight: bold; }
    Root cause:Confusing zero-based counting or negative numbers with nth-child formula rules.
    Key Takeaways
    Nth-child selects elements based on their position among siblings using a simple counting formula starting at 1.
    The formula 'an+b' allows selecting repeating patterns like every 2nd or 3rd element, enabling flexible styling.
    Nth-child counts all element siblings regardless of type; for selecting by tag type, use nth-of-type instead.
    Combining nth-child with other selectors creates powerful, precise CSS rules but requires careful understanding to avoid mistakes.
    Knowing browser behavior and performance considerations helps write reliable and efficient nth-child selectors in real projects.

    Practice

    (1/5)
    1. What does the CSS selector li:nth-child(3) select?
    easy
    A. The third <li> element inside its parent
    B. Every third <li> element in the whole document
    C. The third child of any type inside the parent
    D. All <li> elements except the third one

    Solution

    1. Step 1: Understand nth-child selector

      The nth-child(n) selector targets the element that is the nth child of its parent, counting all types of children.
    2. Step 2: Apply to li:nth-child(3)

      This means it selects the li element only if it is the third child of its parent. It does not select the third li if other elements come before it.
    3. Final Answer:

      The third child of any type inside the parent -> Option C
    4. Quick Check:

      li:nth-child(3) = third child of any type [OK]
    Hint: Selects element if it is nth child of parent, not nth of type [OK]
    Common Mistakes:
    • Thinking it selects the nth element of that type globally
    • Confusing nth-child with nth-of-type selector
    • Assuming it selects every nth element regardless of type
    2. Which of the following is the correct syntax to select every even div inside a container using :nth-child?
    easy
    A. div:nth-child(2n+1)
    B. div:nth-child(even)
    C. div:nth-child(odd)
    D. div:nth-child(2n-1)

    Solution

    1. Step 1: Recall even keyword meaning

      The keyword even in :nth-child(even) selects all even-numbered children (2nd, 4th, 6th, etc.).
    2. Step 2: Match syntax to select even div elements

      Using div:nth-child(even) selects every div that is an even child of its parent.
    3. Final Answer:

      div:nth-child(even) -> Option B
    4. Quick Check:

      even = every 2nd child [OK]
    Hint: Use 'even' keyword to select every 2nd child easily [OK]
    Common Mistakes:
    • Using odd instead of even
    • Using formulas like 2n+1 which select odd children
    • Confusing nth-child with nth-of-type
    3. Given this HTML:
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
      <li>Five</li>
    </ul>

    And CSS:
    li:nth-child(2n) { color: red; }

    Which list items will appear red in the browser?
    medium
    A. Only Two
    B. One, Three, and Five
    C. All list items
    D. Two and Four

    Solution

    1. Step 1: Understand 2n in nth-child

      The formula 2n selects every even child: 2nd, 4th, 6th, etc.
    2. Step 2: Apply to the list items

      Items 2 (Two) and 4 (Four) are even children, so they get the red color.
    3. Final Answer:

      Two and Four -> Option D
    4. Quick Check:

      2n = even children = Two, Four [OK]
    Hint: 2n selects even children: 2,4,6... [OK]
    Common Mistakes:
    • Thinking 2n selects odd children
    • Confusing nth-child with nth-of-type
    • Assuming all items get styled
    4. What is wrong with this CSS if the goal is to color every 3rd p element blue?
    p:nth-child(3n+1) {
      color: blue;
    }
    medium
    A. It colors the 1st, 4th, 7th p, not every 3rd
    B. Syntax error in the formula
    C. It colors only the 3rd p element
    D. It colors all p elements

    Solution

    1. Step 1: Analyze the formula 3n+1

      The formula 3n+1 selects children at positions 1, 4, 7, 10, ...
    2. Step 2: Compare with the goal of every 3rd element

      Every 3rd element means positions 3, 6, 9, ... which is 3n, not 3n+1.
    3. Final Answer:

      It colors the 1st, 4th, 7th <p>, not every 3rd -> Option A
    4. Quick Check:

      3n+1 = 1,4,7... not every 3rd [OK]
    Hint: Use 3n for every 3rd, not 3n+1 [OK]
    Common Mistakes:
    • Using 3n+1 instead of 3n for every 3rd child
    • Confusing formula offsets
    • Expecting 3n+1 to select 3rd, 6th, 9th
    5. You want to style only the 2nd and 4th li elements inside a ul without styling the 6th or others. Which CSS selector achieves this?
    hard
    A. li:nth-child(2), li:nth-child(4)
    B. li:nth-child(2n)
    C. li:nth-child(2n+2)
    D. li:nth-child(2n):not(:nth-child(6))

    Solution

    1. Step 1: Understand the goal

      We want to style only the 2nd and 4th li elements, excluding the 6th or any others.
    2. Step 2: Evaluate each option

      li:nth-child(2n):not(:nth-child(6)) selects every even li except the 6th, but also includes 8th, 10th, etc. li:nth-child(2n) selects all even li elements (2nd, 4th, 6th, ...). li:nth-child(2n+2) selects 2nd, 4th, 6th, ... as well. li:nth-child(2), li:nth-child(4) explicitly selects only the 2nd and 4th li elements.
    3. Final Answer:

      li:nth-child(2), li:nth-child(4) -> Option A
    4. Quick Check:

      Explicitly list 2nd and 4th for exact selection [OK]
    Hint: List exact children with commas for precise selection [OK]
    Common Mistakes:
    • Using formulas that select more than needed
    • Trying to exclude with :not() but missing others
    • Assuming 2n+2 excludes 6th child