CSS Child vs Descendant selectors

Last Updated : 24 Sep, 2024

In CSS, child and descendant selectors are used for targeting elements based on their hierarchical relationships in the HTML structure. These selectors allow you to apply styles with precision and control. This article will help you understand the differences between these two selectors and provide examples of how to use them effectively.

Child Selector(>)

The child selector (element > element) is used to select elements that are direct children of a specified element. This means that only elements immediately nested inside the parent element are selected.

Syntax: 

element > element {
    // CSS Property
}

Example: Match all <p> elements that are child of only <div> element. 

html
<!DOCTYPE html>
<html>

<head>
    <title>
        CSS child Selector
    </title>
    <style>
        div > p {
            color:white;
            background: green;
            padding:2px;
        }
    </style>
</head>

<body style="text-align: center;">
    <div>
        <h2 style="color:green;">
            CSS Child Selector
        </h2>

        <p>
            A computer science portal for geeks.
        </p>
    </div>

    <p>
          Geeks Classes is a quick course to cover
        algorithms questions.
      </p>

    <p>
          This paragraph will not be styled.
      </p>
</body>

</html>

Output:

elements

Descendant Selector (Space)

The descendant selector (element element) targets all descendant elements, including children, grandchildren, and further nested elements, of a specified element. This selector matches any element that is a descendant, not just direct children.

Syntax: 

element element {
    // CSS Property
}

Example: It selects all the <h2> elements which are child elements of <div>. 

html
<!DOCTYPE html>
<html>

<head>
    <title>
        CSS Descendant Selector
    </title>

    <style>
        div h2 {
            font-size:26px;
        }
    </style>
</head>

<body style="text-align:center;">
    <div>
        <h2 style="color:green;">
            GeeksForGeeks
        </h2>

        <div>
            <h2>GeeksForGeeks</h2>
        </div>
    </div>

    <p>
        GeeksforGeeks in green color is
        example of child Selector
        <br>other GeekforGeeks is example
        of descendant Selector
    </p>
</body>

</html>

Output: Child and descendant selectors are used in CSS that allow you to target elements based on their relationships within the HTML document structure. The child selector (>) applies styles only to direct children of an element, while the descendant selector (space) targets all elements nested within a specified ancestor.

Comment