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.

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.

Syntax: 

element > element {
// CSS Property
}

Example: Match all <p> element 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 Beginner.
        </p>
    </div>

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

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

</html>

Output:

elements

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 GeekforBeginner 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.


Contact Us