Nth-child() targets elements based on their position within a specific parent element. It offers precise control over styling elements based on their order.
Syntax
selector:nth-child(n) {
/* Styles to apply */
}
selector: The parent element containing the elements you want to target.
n: The formula used to specify which children to match:
- Specific index:
nis a positive integer representing the child’s position (e.g.,nth-child(2)targets the second child). - Even/odd:
nis one of these keywords:even(matches even-numbered children)odd(matches odd-numbered children)
- Formula:
nis a formula using arithmetic operators (+,-,*,/) and keywords like2n,3n,4n+1, etc.
Examples
- Target the second child
.parent-element:nth-child(2) {
color: blue;
}
- Target even-numbered children
.parent-element:nth-child(even) {
background-color: #f0f0f0;
}
- Target every third child
.parent-element:nth-child(3n) {
font-weight: bold;
}
- Target children starting from the fourth, every other child
.parent-element:nth-child(4n+1) {
border: 1px solid #ccc;
}
Key Points
nth-childstarts counting from 1, not 0.- The formula
ncan be complex to understand, but it offers great flexibility. - You can combine
nth-childwith other selectors for more specific targeting. - If you need to target elements based on their type or class, consider using
:nth-of-typeor:nth-of-a-kind.