Open In App

How to get specific number of child elements using CSS?

The :nth-child() in CSS Selector is used to select only those elements that are the nth child, regardless of type, of its parent.

Syntax:



: nth-child(arg) {
    // CSS Property;
} 

where arg is an argument that represents the pattern for matching elements. It can be number, odd, even or linear equation.

Example 1: This example selects the element which is passed as the argument.




<!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: This example selects the even child elements.




<!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: This example selects the odd child elements.




<!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: This example takes the linear equation as an argument.




<!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:


Article Tags :