Child Selectors

Child selectors provide a way to select elements that fall within one another, thus making them children of their parent element. These selections can be made two different ways, using either descendant or direct child selectors.

Descendant Selector

The most common child selector is the descendant selector, which matches every element that follows an identified ancestor. The descendant element does not have to come directly after the ancestor element inside the document tree, such as a parent-child relationship, but may fall anywhere within the ancestor element. Descendant selectors are created by spacing apart elements within a selector, creating a new level of hierarchy for each element list.

Below, the headings are lines 3 and 5 are selected.

article h2 {...}
<h2>...</h2>
<article>
  <h2>This heading will be selected</h2>
  <div>
    <h2>This heading will be selected</h2>
  </div>
</article>
Direct Child Selector

Sometimes descendant selectors go a bit overboard, selecting more than hoped. At times only the direct children of a parent element need to be selected, not every instance of the element nested deeply inside of an ancestor. In this event the direct child selector may be used by placing a greater than sign, >, between the parent element and child element within the selector.

Below, the paragraph on line 3 is the only direct child of it’s parent article, thus selected.

article > p {...}
<p>...</p>
<article>
  <p>This paragraph will be selected</p>
  <div>
    <p>...</p>
  </div>
</article>
Example Classification Explanation
article h2 Descendant Selector Selects an element that resides anywhere within an identified ancestor element
article > p Direct Child Selector Selects an element that resides immediately inside an identified parent element