Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Selectors Selectors - Beyond the Basics Child, Adjacent, and General Sibling Combinators

Difference between Descendant and Child selectors

As Guil told the use of Descendant and Child selectors, there seems no difference between them to me.

3 Answers

Imagine four paragraphs nested directly within a div. Both the descendant and child selectors will target these paragraphs. However, if the original div contained another div at the same level of the previously-mentioned paragraphs which contained an additional paragraph, this last paragraph would be targeted by the descendent but not the child selector:

<div class="first">
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <div class="second">
          <p></p>
    </div> 
</div>
.first p {
    /*** This will target all the <p> elements in the HTML above ***/
}

.first > p {
    /*** This will target all <p> elements except the one nested within the "second" class ***/
}

I've added to my answer. Refresh and check it out. Hope it helps :)

James, what if the nested div had the class of first then both the descendant and the child selector could be used.

Yes. If the nested div also had the "first" class, there would be no difference between using descendent/child selectors. The same would apply if the divs in question had no class assigned to them; in certain cases, identical results will obtain.

Thanks James.

Jake Ford
Jake Ford
9,230 Points

Great explanation, James!

Anthony c
Anthony c
20,907 Points

So,

descendent = every specified element that follows

and child = only specified elements that very directly follow

Is this right?

Yes, I think you've understood correctly. Maybe instead of saying "every specified element that follows" you should say "any element whatsoever that follows" because there is no need to specify anything.

Consider it this way: you're the child of some woman (your mother), but YOUR children wouldn't be considered her children (they would, however, be her descendants).

Dayne Wright
Dayne Wright
11,235 Points

This helped me a lot as well. Thanks!

you're welcome!