CSS `:nth-child(n)` Selector: Precisely Targeting Elements by Position
Master precise element selection in CSS using the powerful `:nth-child(n)` selector. This tutorial explains how to use numbers, keywords (`odd`, `even`), and formulas to target elements based on their position within a parent container, enabling sophisticated and flexible styling techniques.
Using the CSS `:nth-child(n)` Selector
Selecting Elements by Position
The CSS `:nth-child(n)` selector allows you to select elements based on their position within a parent container. Unlike other selectors that target elements by type, ID, or class, `:nth-child()` selects elements based solely on their order (index) among their siblings. The `n` can be a number, keyword (`odd`, `even`), or a formula.
` :nth-child(n)` Syntax
The basic syntax is:
:nth-child(n) { /* CSS properties */ }
Where `n` specifies the selection pattern. `n` can be:
- A number (e.g., `:nth-child(3)` selects the third child).
- The keyword `odd` (selects odd-numbered children).
- The keyword `even` (selects even-numbered children).
- A formula of the form `An + B` (where `A` and `B` are integers, and `n` starts at 0). This allows for more complex selection patterns (e.g., `:nth-child(3n+1)` selects the first element of every group of 3).
Examples of `:nth-child(n)`
Example 1: Using a Formula
This example uses the formula `3n + 4`. This will select the 4th, 7th, 10th, etc. children. The provided code is illustrative; you would need to include HTML elements within a container to see the effect. The first child has an index of 1.
CSS Code
p:nth-child(3n+4) {
color: red;
}
Example 2: Using `odd` and `even` Keywords
This example shows how to target odd and even-numbered children using the keywords `odd` and `even`. Again, this requires corresponding HTML elements in your document to function.
CSS Code
p:nth-child(odd) {
background-color: lightblue;
}
p:nth-child(even) {
background-color: lightgreen;
}