DEV Community

Cover image for Difference between Child Selector and Descendant Selector
Md Shahab Uddin
Md Shahab Uddin

Posted on

Difference between Child Selector and Descendant Selector

Sometimes we confuse Child Selector with Descendant Selector. Here is an easy explanation on this topic.

*Example 1: *
Suppose you have one brother , one sister and one cousin. As you know that All of you are descendant of your grandfater. But Your father is direct child of your grandfather.

*Example 2: *

You are child of your fater but your son isn't child of your fater but they are descendant of your fater.

Now let's apply this rule in CSS selector
Look the below html code. I have a section which has one paragraph element. Inside the section element there is one div and inside the div there is one paragraph element.
So we can conclude that:

  • First paragraph is child of section element
  • Second paragraph is descendant of section element
 <section>
     <p class="first">This is first Paragraph</p>
     <div>
       <p class="second">This is second paragraph </p>
     </div>
   </section>

Enter fullscreen mode Exit fullscreen mode

IF i use this code:

section p {
     background-color: red;
}
Enter fullscreen mode Exit fullscreen mode

The above code will be applied on both first and second paragrpah because they both are descendant of section.
But if i use this code:

section > p {
  background-color: red;
}
Enter fullscreen mode Exit fullscreen mode

This above code will be applied only on first paragraph because only this paragraph is direct child of the section.

Top comments (0)