Role of CSS :nth-child(n) Selector

The CSS :nth-child(n) selector allows you to select and style elements based on their position among siblings within a parent element. This powerful pseudo-class selector enables precise targeting of specific child elements without adding extra classes or IDs.

Syntax

selector:nth-child(n) {
    property: value;
}

Possible Values

Value Description
odd Selects every odd-numbered child
even Selects every even-numbered child
n Specific position number (1, 2, 3, etc.)
an+b Formula for complex patterns

Example 1: Selecting Specific Position

The following example styles the fourth paragraph element with an orange background −

<!DOCTYPE html>
<html>
<head>
<style>
    p:nth-child(4) {
        background: orange;
        color: white;
        padding: 10px;
        margin: 5px 0;
    }
    p {
        margin: 5px 0;
        padding: 5px;
        background: #f0f0f0;
    }
</style>
</head>
<body>
    <p>This is demo text 1.</p>
    <p>This is demo text 2.</p>
    <p>This is demo text 3.</p>
    <p>This is demo text 4.</p>
    <p>This is demo text 5.</p>
    <p>This is demo text 6.</p>
</body>
</html>
Six paragraphs appear on the page. The fourth paragraph has an orange background with white text and padding, while the others have a light gray background.

Example 2: Selecting Odd and Even Children

The following example demonstrates styling odd and even child elements differently −

<!DOCTYPE html>
<html>
<head>
<style>
    li:nth-child(odd) {
        background: #e6f3ff;
        color: #0066cc;
    }
    li:nth-child(even) {
        background: #fff2e6;
        color: #cc6600;
    }
    li {
        padding: 8px;
        margin: 2px 0;
        list-style: none;
    }
</style>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>
</body>
</html>
A list with alternating colors: odd items (1, 3, 5) have a light blue background with blue text, while even items (2, 4) have a light orange background with orange text.

Conclusion

The :nth-child(n) selector provides flexible element selection based on position. Use specific numbers for precise targeting, or odd/even keywords for alternating patterns in lists and tables.

Updated on: 2026-03-15T12:21:29+05:30

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements