Difference between Child Selector and Descendant Selector

shahab570

Md Shahab Uddin

Posted on May 29, 2021

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.

💖 💪 🙅 🚩
shahab570
Md Shahab Uddin

Posted on May 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024