The :nth-child() selector helps you pick specific elements based on their order inside a parent. It makes styling easier when you want to target items by their position.
Nth-child selector in CSS
:nth-child(an+b) { /* styles */ }an+b is a formula where a and b are numbers. For example, 2n+1 means every odd child.
You can also use keywords like odd or even instead of the formula.
li:nth-child(3) { color: red; }
tr:nth-child(even) { background-color: #f0f0f0; }
p:nth-child(2n+1) { font-weight: bold; }
div:nth-child(-n+4) { border: 1px solid blue; }
This example shows a shopping list where every even item has a light blue background. The 3rd item is styled with red bold text to stand out. This uses :nth-child(even) and :nth-child(3) selectors.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Nth-child Selector Example</title> <style> ul { list-style: none; padding: 0; max-width: 200px; margin: 1rem auto; font-family: Arial, sans-serif; } li { padding: 0.5rem; border: 1px solid #ccc; margin-bottom: 0.25rem; text-align: center; } /* Color every even item light blue */ li:nth-child(even) { background-color: #d0e7ff; } /* Make the 3rd item text red and bold */ li:nth-child(3) { color: #b22222; font-weight: bold; } </style> </head> <body> <main> <h1>Shopping List</h1> <ul aria-label="Shopping list"> <li>Milk</li> <li>Bread</li> <li>Eggs</li> <li>Cheese</li> <li>Apples</li> <li>Bananas</li> </ul> </main> </body> </html>
The :nth-child() selector counts elements of the same parent, regardless of their class or type.
Remember it counts all child elements, so if you want to target only certain types, combine it with the element name, like li:nth-child(2).
Use browser DevTools to inspect and test :nth-child() styles live for better understanding.
:nth-child() lets you style elements based on their position inside a parent.
You can use formulas or keywords like odd and even to select multiple elements.
This selector helps create patterns like stripes or highlight specific items without extra HTML.