Search notes:

CSS selectors: children and descendants

p > c matches element c if c is a direct descendant (a child) of p.
p d matches element d if d is a direct or indirect descendant (a child or grand-child, or grand-grand-grand-child …) of p.
The following HTML document tries to demonstrate these selectors:
<!DOCTYPE html>
<html>
<head>

  <title>Match children and descendants</title>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <!-- HTML5 (?) <meta charset="utf-8"> -->

   <style type='text/css'>

     .match-here   .match-if-descendent { /* Rule 1*/
       color           : maroon;
       background-color: greenyellow;
     }

     .match-here > .match-if-child {      /* Rule 2 */
       color           : yellow;
       background-color: red;
     }

     div {
       border: 1px solid black;
       margin: 5px;
       background-color: #eee;
     }

     div > div {
       background-color: #ccc;
     }

     div > div > div {
       background-color: #aaa;
     }

   </style>
  

</head>
<body>

  <div class='match-here'>

    This is the <code>.match-here</code> div.

    <div class='xyz'>
       This div does not match, its class is <code>.xyz</code>

       <div class='match-if-descendent'>
         This is a <code>.match-if-descendent</code> div. It matches <i>Rule 1</i> because it's a (direct or indirect) descendent of <code>.match-here</code> 
        (the corresponding selector is <code>.match-here   .match-if-descendent</code>)
       </div>

       <div class='match-if-child'>
         This is a <code>.match-if-child</code> div. It doesn't match because it is not a (direct) child of <code>.match-here</code>
        (the corresponding selector is <code>.match-here &gt; .match-if-child</code>).
       </div>

    </div>

    <div class='match-if-descendent'>
      This div matches <i>Rule 1</i> because it's a (direct or indirect) descendent of <code>.match-here</code>.
    </div>

    <div class='match-if-child'>
      This div matches <i>Rule 2</i> because it's a direct descendent of <code>.match-here</code>.
    </div>

  </div>

  <p>

  <div class='dont-match'>
   
    This is the <code>.dont-match</code> div.

    <div class='match-if-descendent'>
      This div does not match the first or second rule.
    </div>

    <div class='match-if-child'>
       Neither does this div.
    </div>


  </div>

</body>
</html>
Github repository about-css, path: /selectors/children-and-descendants.html

See also

CSS selectors

Index