Selecting a child element

I know two ways to select a child element, article > p and article p but which is better?

Hi, there!

So both of these selector methods select the children on the parent element, but their behaviors vary.

Let’s take look at HTML that uses your example:

<article>
  <p>I am a child</p>
  <section>
    <p>I am a grand-child</p>
  </section>
  <p>I am another child</p>
</article>

So, in this example, there are 3 <p> elements.

If I were to use something like this:

article p {
  color: red;
}

The output would look like so:
image

But if I use this selector:

article > p {
  color: red;
}

This is the output:
image

The article p selector selects all of the p children of the parent article, while the article > p selector selects only the direct children of the parent article.

So, the case in which you use it will depend on what you’re trying to accomplish. Does that make sense?

5 Likes

Yes! Thanks so much for the help!

2 Likes