CSS :nth-child() Selector

The :nth-child() CSS pseudo-class selector is useful for targeting elements based on their position among siblings. This selector can match elements by specific numeric positions, odd/even positions, or complex functional notations like An+B. Understanding and utilizing :nth-child() can enhance web design by allowing for precise and dynamic styling of HTML elements.

Syntax:

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

Where number is the single 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. Here, A represents the integer step size, and B represents the integer offset.

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

HTML
<!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;">
        w3wiki
    </h1>
    <h2>
        CSS :nth-child Selector
    </h2>

    <p>
        A computer science portal for Beginner.
    </p>

    <p>
        Beginner classes an extensive classroom programme.
    </p>

</body>

</html>

Output:

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

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

Output:

Utilizing the :nth-child() CSS pseudo-class selector can greatly improve the flexibility and specificity of your web designs. Whether styling every odd or even element or using complex patterns, mastering this selector enables developers to create more dynamic and responsive layouts. Incorporating :nth-child() into your CSS toolkit will enhance the efficiency and creativity of your web development projects.

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

  • Google Chrome 1.0
  • Microsoft Edge 12.0
  • Firefox 3.5
  • Opera 9.5
  • Apple Safari 3.1

Contact Us