The CSS Child Selector

In a recent post, Descendant Selectors in CSS, you saw that a descendant selector takes this form: #content p. That selector would style every p element that was a descendant of a content element. A child selector is similar, except it doesn’t select every descendant, it selects only immediate descendants of an element (or children). The syntax is element > element.

For example, to select only those paragraphs that are immediate descendants of a blockquote element, you can use the child selector blockquote > p.

Suppose your HTML looked like this:

<blockquote>
<p></p>
<p></p>
</blockquote>

The p elements are immediate descendants, or children, of the blockquote. A CSS rule like

blockquote > p {color: red;}

would style every paragraph element in the previous HTML structure.

However, if the structure of your blockquote was this HTML:

<blockquote>
<p></p>
<div>

<p></p>
</div>
</blockquote>

The second paragraph element is not an immediate child of the blockquote. It is the immediate child of a div element. Using the blockquote > p {color: red;} selector, only the first paragraph (the child) would display in red in that HTML structure.