Tuesday, 12 November 2024

CSS Child Selector to target Direct Descendants

The child selector (>) in CSS is used to select elements that are direct children of a specified parent element. It targets only those child elements that are immediate descendants of a parent, excluding any further nested descendants.

Syntax

parent > child {
  /* styles */
}

 

1.   parent: The parent element.

2.   child: The direct child element that you want to style.

 

childSelector.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Child Selector Example</title>
    <link rel="stylesheet" href="../../css/selectors/childSelector.css">
</head>
<body>
    <div class="container">
        <p>This paragraph is inside the container.</p>
        <div>
            <p>This paragraph is inside a nested div.</p>
        </div>

        <span>This span is inside the container.</span>
    </div>
</body>
</html>

 

childSelector.css

.container > p {
    color: blue;
    font-weight: bold;
}

.container > span {
    color: red;
    font-style: italic;
}

Open ‘childSelector.html’ in browser, you can see below screen.


.container > p

This style applies styles only to the direct p child of .container. In this case, the first p element gets styled with blue text and bold font-weight. The second p inside the nested div is not affected because it's not a direct child of .container.

 

.container > span

This style targets the direct span child of .container, applying red text color and italic font style.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment