CSS | :nth-child() Selector

The :nth-child() selector in CSS is used to match the elements based on their position in a group of siblings. It matches every element that is the nth child.

Syntax:

:nth-child(number) {
    //CSS Property
}

Where number is the argument that represents the pattern for matching elements. It can be odd, even or in a functional notation.

  • odd: It represents elements whose position is odd in a series: 1, 3, 5, etc.
  • even: It represents the elements whose position is even in a series: 2, 4, 6, etc.
  • functional notation (<An+B>): It represents elements whose position of siblings matches the pattern An+B, for every positive integer or zero value of n.

Example-1: In this example every odd paragraph is selected. Formula used is 2n+1 i.e 1, 3, 5, etc paragraphs are selected.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>CSS :nth-child Selector</title>
        <style
            p:nth-child(2n+1) {
              background: green;
              color: white;
            }
        </style>
    </head>
    <body style = "text-align:center">
        <h1 style = "color:green;">
            GeeksforGeeks
        </h1>
        <h2>
            CSS :nth-child Selector
        </h2>
      
        <p>A computer science portal for geeks.</p>
        <p>Geeks classes an extensive classroom programme.</p>
          
    </body>
</html>

chevron_right


Output:
nthchild
Example-2: In this example every even <li> is selected i.e. 2, 4, 6, etc.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>CSS :nth-child Selector</title>
        <style
        li {
            width: 30%;
        }
            li:nth-child(even) {
              background: green;
              color: white;
            }
        </style>
    </head>
    <body style = "text-align:center">
        <h2>
            CSS :nth-child Selector
        </h2>
        <p>Sorting Algorithms</p>
        <ul>
        <li>Quick sort.</li>
        <li>Merge sort.</li>
        <li>Insertion sort.</li>
        <li>Selection sort.</li>
          
        </ul>
          
    </body>
</html>

chevron_right


Output:
nthchild

Supported Browsers: The browser supported by :nth-child() selector are listed below:

  • Apple Safari 3.2
  • Google Chrome 4.0
  • Firefox 3.5
  • Opera 9.6
  • Internet Explorer 9.0


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.