CSS Descendant & Child Selector


CSS descendant and CSS child combinators, both used for selecting elements based on a specified hierarchical relationship with an HTML element.

CSS Descendant Selector

  • Selects all elements that are descendants (children, grandchildren, great-grandchildren, etc.) of a specified element.
  • Symbol: A space between selectors.
ancestor descendant {
  property: value;
} 

css-descendant-selector-and-child-selector


Example

 <!DOCTYPE html>
<html>
<head>
  <style>
    div p {
      color: darkgreen;
      font-weight: bold;
    }
  </style>
</head>
<body>

<div>
  <p>This paragraph is inside a div.</p>
  <section>
    <p>This nested paragraph is also inside the div.</p>
  </section>
</div>

<p>This paragraph is outside the div and not affected.</p>

</body>
</html>

CSS Child Selector

  • Selects elements that are direct children only of a specified parent.
  • Symbol: A greater-than sign (>) between selectors.

Syntax

parent > child {
  property: value;
} 

Example

<!DOCTYPE html>
<html>
<head>
  <style>
    div > p {
      color: crimson;
      font-style: italic;
    }
  </style>
</head>
<body>

<div>
  <p>This paragraph is a direct child of div.</p>
  <section>
    <p>This paragraph is nested and NOT affected.</p>
  </section>
</div>

<p>This paragraph is outside the div and not affected.</p>

</body>
</html> 

Difference Between Descendant and Child Selector

Feature Descendant Selector ( ) Child Selector (>)
Relationship Any level (child, grandchild) Direct child only
Symbol (space) >
Example div p div > p
Matches All <p> inside <div> Only <p> directly inside <div>



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.