CSS: differences between descendant and child selectors

I noticed that many developers who start coding in CSS sometimes get confused by descendant and child selectors. In a nutshell: descendant selectors select an element that is contained within another element, disregarding its position in the DOM tree. On the contrary, child selectors select an element only when it's the direct child of its parent. For example, given the following structure:

<div>

    <p>
        <em>Test</em>
    </p>

</div>

You can use descendant selectors this way:

div em  {
  background: yellow;
}

Notice that in this case the matching occurs without taking into account the order of the DOM tree. Instead, if you use child selectors, you have to write this:

p > em {
  background: yellow;
}

That's because the em element is the direct child of the p element. In this case the inner order of the DOM tree is relevant.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “CSS: differences between descendant and child selectors”

Leave a Reply

Note: Only a member of this blog may post a comment.