Descendant selector

The descendant selector (element element) selects all elements that are descendants of a specified element, not just direct children. It combines two selectors such that elements matched by the second selector are selected if they have an ancestor matching the first selector.

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;">
            w3wiki
        </h2>

        <div>
            <h2>w3wiki</h2>
        </div>
    </div>

    <p>
        w3wiki 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 powerful tools in CSS for targeting elements based on their hierarchy. The child selector targets direct children, while the descendant selector targets all descendants. Understanding and using these selectors effectively can enhance your ability to style web pages precisely.


CSS Child vs Descendant selectors

Understanding the differences between child and descendant selectors in CSS is crucial for precise styling. These selectors allow you to target HTML elements based on their hierarchical relationships, ensuring you apply styles accurately.

Similar Reads

Child Selector:

The child selector (element > element) matches all elements that are direct children of a specified element. The element on the left side of > is the parent, and the element on the right is the child....

Descendant selector:

The descendant selector (element element) selects all elements that are descendants of a specified element, not just direct children. It combines two selectors such that elements matched by the second selector are selected if they have an ancestor matching the first selector....