The :nth-child()
pseudo-class is a more flexible selector that targets elements based on their position using a number, keyword (odd or even), or a formula. This allows for complex striping patterns and other advanced selections.
Example 1: Styling Even and Odd Rows
/* Styles even and odd list items differently */
li:nth-child(odd) {
background-color: #f9f9f9;
}
li:nth-child(even) {
background-color: #eee;
}
Explanation
This code creates a "zebra-striped" effect on a list by applying a slightly different background color to odd and even list items.
Example 2: Highlighting a Specific Item
/* Targets the third list item */
li:nth-child(3) {
font-weight: bold;
}
Explanation
This CSS selects only the third list item (<li>
) in a list and makes its text bold, useful for calling out a specific item.
Example 3: Styling in Groups
/* Styles every third element starting from the first */
.gallery-item:nth-child(3n+1) {
clear: left;
}
Explanation
This rule targets gallery items with the class .gallery-item
in a pattern of every third item, starting with the first one (1
, 4
, 7
, etc.). It's often used to clear floats in a grid layout.
Example 4: Selecting the First Few Elements
/* Targets the first three <div> elements */
div:nth-child(-n+3) {
border: 1px solid #007bff;
}
Explanation
This CSS applies a blue border to the first three <div>
elements within a parent container. The formula -n+3
selects all elements from the first up to the third.
Example 5: Skipping the First Few Elements
/* Targets all list items except the first two */
li:nth-child(n+3) {
display: none;
}
Explanation
This code hides all list items (<li>
) starting from the third one. The formula n+3
selects all elements from the third to the end.