CSS nth-child Selectors Complete Guide: Master Element Selection
 
 Why Master nth-child Selectors?
Imagine needing to apply different styles to specific items in a list: change color every three elements, add background to odd rows, special treatment for the first five elements… Traditional approaches require adding different classes to each element - tedious and inelegant.
CSS nth-child selectors allow you to:
- Precisely target elements at any position without extra classes
- Dynamically respond to content changes with automatic style application
- Reduce HTML markup, keeping code cleaner
- Implement complex patterns like table zebra stripes, grid layouts, etc.
This article will help you completely master this powerful CSS selector through extensive interactive examples!
Basic nth-child Selectors
Let’s start with the most basic usage patterns and understand how each selector works through visual examples.
Basic nth-child Selector Demonstration
Basic Selector Code Analysis
The examples above demonstrate the most commonly used nth-child selectors. Let’s understand each syntax in detail:
Numeric Selection
/* Select the 2nd element */
.item:nth-child(2) {
  background: blue;
}
/* Shorthand for selecting the 1st element */
.item:first-child {
  background: green;
}
/* Shorthand for selecting the last element */
.item:last-child {
  background: orange;
}Odd/Even Selection
/* Select odd positions (1, 3, 5, 7...) */
.item:nth-child(odd) {
  background: purple;
}
/* Select even positions (2, 4, 6, 8...) */
.item:nth-child(even) {
  background: pink;
}Multiple Selection
/* Select multiples of 3 (3, 6, 9, 12...) */
.item:nth-child(3n) {
  background: cyan;
}Important Concepts:
- nth-childcounts from 1, not from 0
- The selector will select all matching child elements
- oddis equivalent to- 2n+1,- evenis equivalent to- 2n
Advanced Mathematical Formula Selectors
The true power of nth-child lies in its mathematical formula functionality. Using the an+b format, you can implement complex selection patterns.
Interactive Mathematical Formula Calculator
Input values for a and b to understand how the an+b formula works
Mathematical Formula Deep Analysis
The mathematical formula an+b in nth-child is key to understanding advanced selectors. Let’s explore in depth:
Formula Structure
:nth-child(an+b)- a: Coefficient, determines interval pattern
- n: Variable, incrementing infinitely from 0 (0, 1, 2, 3…)
- b: Offset, adjusts starting position
Common Formula Examples
/* Odd elements = 2n+1 */
:nth-child(2n+1)  /* n=0: 1, n=1: 3, n=2: 5... */
/* Even elements = 2n */
:nth-child(2n)    /* n=1: 2, n=2: 4, n=3: 6... */
/* Every third = 3n */
:nth-child(3n)    /* n=1: 3, n=2: 6, n=3: 9... */
/* First five = -n+5 */
:nth-child(-n+5)  /* n=0: 5, n=1: 4, n=2: 3, n=3: 2, n=4: 1 */
/* Every 2nd starting from 3rd = 2n+3 */
:nth-child(2n+3)  /* n=0: 3, n=1: 5, n=2: 7... */Clever Use of Negative Coefficients
/* Select first N elements */
:nth-child(-n+3) { /* Select first 3 */ }
:nth-child(-n+5) { /* Select first 5 */ }
/* Select middle range */
:nth-child(n+3):nth-child(-n+7) { /* Select 3rd to 7th */ }Practical Application Scenarios
/* Table zebra stripes */
tr:nth-child(even) { background: #f5f5f5; }
/* Grid layout last in each row */
.grid-item:nth-child(4n) { margin-right: 0; }
/* Article list highlight every 5th */
.article:nth-child(5n) { border-left: 4px solid blue; }Real-world Application Scenarios
After mastering the basic syntax, let’s see the powerful applications of nth-child in real projects.
Real-world Application Scenarios Showcase
| Product Name | Price | Stock | 
|---|---|---|
| iPhone 15 | $999 | 50 | 
| MacBook Pro | $1299 | 25 | 
| iPad Air | $599 | 75 | 
| Apple Watch | $399 | 100 | 
| AirPods Pro | $249 | 200 | 
Steps 1-3 completed, currently on step 4
Real-world Application Code Breakdown
The examples above show specific applications of nth-child in real projects. Let’s analyze the implementation of each scenario:
Table Zebra Stripe Effect
/* Even row background color */
.table tr:nth-child(even) {
  background-color: #f5f5f5;
}
/* Can also use odd rows */
.table tr:nth-child(odd) {
  background-color: #ffffff;
}Grid Layout Special Treatment
/* Remove right margin from last element in each row */
.grid-item:nth-child(3n) {
  margin-right: 0;
}
/* Add border to first row elements */
.grid-item:nth-child(-n+3) {
  border-top: 3px solid blue;
}Navigation Menu Styling
/* Special style for first menu item */
.nav-item:first-child {
  background: #primary-color;
  color: white;
}
/* Even menu items background */
.nav-item:nth-child(even) {
  background: #light-gray;
}Content List Highlighting
/* Highlight every 5th item */
.article:nth-child(5n) {
  background: #highlight-color;
  border-left: 4px solid #accent-color;
}
/* Special treatment for first item */
.article:first-child {
  font-weight: bold;
  background: #featured-color;
}Progress Indicator
/* Completed steps (first N) */
.step:nth-child(-n+3) {
  background: #success-color;
  color: white;
}
/* Current step */
.step:nth-child(4) {
  background: #current-color;
  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2);
}Practical Tips Summary:
- Tables: Use even/oddto improve readability
- Grids: Use 3n, 4netc. to handle last elements in each row
- Lists: Use 5n, 10nto highlight important content
- Steps: Use -n+Nto show completion status
- Navigation: Use :first-child, :last-childto handle boundaries
Advanced Techniques and Best Practices
After mastering the basics, let’s explore some advanced nth-child usage and best practices in actual development.
Compound Selector Usage
Range Selection
/* Select elements 2 to 5 */
.item:nth-child(n+2):nth-child(-n+5) {
  background: yellow;
}
/* Select odd elements excluding certain ones */
.item:not(:nth-child(3)):nth-child(odd) {
  color: blue;
}Combined with Type Selectors
/* Select only odd positioned <p> elements */
p:nth-child(odd) {
  margin-left: 20px;
}
/* Every 3rd <img> element */
img:nth-child(3n) {
  border-radius: 50%;
}Performance Optimization Recommendations
Avoid Overuse
/* ❌ Poor performance */
.item:nth-child(2n+1):nth-child(-n+10):not(.special) {
  /* Complex compound selectors */
}
/* ✅ Better performance */
.item:nth-child(odd) {
  /* Simple selectors */
}
.item.first-ten:nth-child(odd) {
  /* Combine with class to reduce complexity */
}Application in Responsive Design
/* Desktop: 4-column layout */
@media (min-width: 768px) {
  .card:nth-child(4n) {
    margin-right: 0;
  }
}
/* Tablet: 3-column layout */
@media (max-width: 767px) {
  .card:nth-child(4n) {
    margin-right: initial; /* Reset desktop style */
  }
  .card:nth-child(3n) {
    margin-right: 0;
  }
}Browser Compatibility
nth-child has good support in modern browsers:
- Supported: Chrome, Firefox, Safari, Edge (all modern versions)
- Not supported: IE8 and below
Compatibility Handling
/* Progressive enhancement approach */
.item {
  background: #default; /* Default style */
}
.item:nth-child(even) {
  background: #enhanced; /* Enhanced style for supported browsers */
}Useful Selector Formula Collection
/* Common pattern quick reference */
:nth-child(odd)        /* Odd: 1,3,5,7... */
:nth-child(even)       /* Even: 2,4,6,8... */
:nth-child(3n)         /* Every 3rd: 3,6,9,12... */
:nth-child(3n+1)       /* Every 3rd+1: 1,4,7,10... */
:nth-child(-n+5)       /* First 5: 1,2,3,4,5 */
:nth-child(n+3)        /* From 3rd onwards: 3,4,5,6... */
:nth-child(2n+3)       /* From 3rd, every 2nd: 3,5,7,9... */
:nth-child(4n-1)       /* Before every 4th: 3,7,11,15... */Master these techniques, and nth-child will become one of the most powerful selectors in your CSS toolkit!
Summary
CSS nth-child selectors are indispensable tools in modern web design. Through this comprehensive guide, you have mastered:
- Basic Syntax: Numbers, odd/even, first/last-child usage
- Mathematical Formulas: Deep understanding and flexible application of an+b formulas
- Real-world Applications: Tables, grids, navigation, lists and other practical scenarios
- Advanced Techniques: Compound selectors, performance optimization, responsive applications
Suggestions for Getting Started:
- Start Simple: Master odd/even and basic number selection first
- Understand Formulas: Take time to understand the calculation principles of an+b
- Practical Application: Try different selection patterns in your projects
- Test and Verify: Use developer tools to verify selector effects
Remember Key Principles:
- nth-child counts from 1, not from 0
- n in formulas starts from 0 and increments
- Negative coefficients can achieve “first N” selection
- Proper use can dramatically reduce HTML markup
The power of CSS nth-child selectors lies in their logic and predictability. Once you master the calculation rules, you can precisely target any desired elements, making style design more flexible and efficient.
Start applying these techniques in your projects now to create more elegant and efficient CSS code!
 
  
  
 