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

Descendant Selector vs Child Selector

I started coding a long while back but am going through a program to kinda refresh myself and get current in my knowledge.

I went through a video on Descendant Selectors, and was wondering when this became the terminology used rather than parent and child selectors. Also was curious if there's any particular reason why one terminology is or might be used over the other.

1 Answer

The reality is, you probably won't hear people using that terminology much either way :). But a legit reason why you'd say "descendant" instead of "child" is because if you write:

.my-div a {
  color: red;
}

That's going to apply to ALL of these, not just immediate (1-level in) children of the .my-div element:

<div class="my-div">
  <a href="/"><img src="./site-logo.png"></a>
  <nav>
    <ul>
       <li><a href="about.html">About</a></li>
       <li><a href="contact.html">Contact</a></li>
    </ul>
  </nav>
  <section>
    <p>Follow me on <a href="http://www.linkedin.com">LinkedIn</a></p>
  </section>
</div>

Most of those are grandchildren/great-grandchildren etc. of the .my-div element, but they are all descendants of it, and they will all inherit that CSS rule.

Ah, makes sense that with the increased nesting that it goes so far beyond the basic parent child relationship that it's easier to call it descendant than try to figure out which generation it is.

Like (and I know this would be bad form) selecting the li in your example you'd have:

div nav ul li {
   color: blue;
}

Where it would be the the great-grandchild (or more if expanded to body main)

Thanks for the answer.