How to select all child elements recursively using CSS?

To select all child elements recursively using CSS, we use the universal selector (*) with a parent selector. This technique allows you to target all descendant elements, regardless of their nesting level.

Syntax

/* Select direct children only */
.parent > * {
    property: value;
}

/* Select all descendants recursively */
.parent * {
    property: value;
}

Example 1: Direct Child Elements Only

This example selects only the direct children of the parent container using the child combinator (>)

<!DOCTYPE html>
<html>
<head>
<style>
    .container > * {
        background-color: #c0a2f0;
        max-width: fit-content;
        margin: 5px 0;
        padding: 5px;
    }
</style>
</head>
<body>
    <h3>Selecting Direct Child Elements Only</h3>
    <div class="container">
        <p>Paragraph 1 (direct child)</p>
        <p>Paragraph 2 (direct child)</p>
        <span>
            <p>Paragraph 3 (nested - not selected)</p>
        </span>
        <p>Paragraph 4 (direct child)</p>
    </div>
    <p>Paragraph 5 (outside container)</p>
</body>
</html>
Paragraphs 1, 2, the span element, and Paragraph 4 have purple background. Paragraph 3 (inside span) and Paragraph 5 (outside container) remain unstyled.

Example 2: All Child Elements Recursively

This example selects all descendant elements recursively using the universal selector without the child combinator

<!DOCTYPE html>
<html>
<head>
<style>
    .container * {
        background-color: #90EE90;
        max-width: fit-content;
        margin: 5px 0;
        padding: 5px;
    }
</style>
</head>
<body>
    <h3>Selecting All Child Elements Recursively</h3>
    <div class="container">
        <p>Paragraph 1 (selected)</p>
        <p>Paragraph 2 (selected)</p>
        <span>
            <p>Paragraph 3 (nested but selected)</p>
        </span>
        <p>Paragraph 4 (selected)</p>
    </div>
    <p>Paragraph 5 (outside container)</p>
</body>
</html>
All paragraphs inside the container (including the nested Paragraph 3) and the span element have green background. Only Paragraph 5 (outside the container) remains unstyled.

Key Differences

Selector Description Targets
.parent > * Direct children only Immediate child elements
.parent * All descendants All nested elements at any level

Conclusion

Use .parent > * to select only direct children, or .parent * to select all descendant elements recursively. The recursive approach is particularly useful for applying consistent styling across deeply nested structures.

Updated on: 2026-03-15T16:43:57+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements