How to get specific number of child elements using CSS?
Last Updated :
01 Oct, 2024
The :nth-child() CSS pseudo-class is used to style elements based on their position in a parent element's child list. This selector allows you to target elements in a specific position or match them based on patterns such as odd or even positions, or by using a linear equation.
Syntax:
element:nth-child(arg) {
/* CSS Properties */
}
Argument Descriptions
where arg is an argument that represents the pattern for matching elements. It can be number, odd, even or linear equation.
- number: It represents the elements whose position is specified by the argument.
- odd: It represents the elements whose position is odd i.e., 1, 3, 5, etc.
- even: It represents the elements whose position is even i.e, 2, 4, 6, etc.
- linear equation: It represents the elements whose position matches the pattern A*n + B, for every positive integer n. Value of n starts with zero.
Example 1: Selecting a Specific Child Element by Position
In this example, we use a specific number as the argument to select the second child of its parent element.
html
<!DOCTYPE html>
<html>
<head>
<style>
p:nth-child(2) {
color: green;
font-weight: bold;
font-size: 20px;
}
</style>
</head>
<body>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
</body>
</html>
Output:

Example 2: Selecting Even Child Elements
This example demonstrates how to use even as the argument to select all even-positioned child elements.
html
<!DOCTYPE html>
<html>
<head>
<style>
p:nth-child(even) {
color: green;
font-weight: bold;
font-size: 20px;
}
</style>
</head>
<body>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
</body>
</html>
Output :

Example 3: Selecting Odd Child Elements
Here, we use odd as the argument to select all odd-positioned child elements.
html
<!DOCTYPE html>
<html>
<head>
<style>
p:nth-child(odd) {
color: green;
font-weight: bold;
font-size: 20px;
}
</style>
</head>
<body>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
</body>
</html>
Output :

Example 4: Using a Linear Equation
In this example, we use a linear equation as the argument to select elements that match a specific pattern. Here, 3n + 1 selects every third child element starting from the first.
html
<!DOCTYPE html>
<html>
<head>
<style>
p:nth-child(3n + 2) {
color: green;
font-weight: bold;
font-size: 20px;
}
</style>
</head>
<body>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
<p>GeeksforGeeks</p>
</body>
</html>
Output: