In this tutorial we will see Difference Between Descendant Selector and Child Selector. Both Descendant and Child Selectors are combinators but both are different.
Table of Contents
Explanation
The difference between Descendant Selector and Child Selector lies in the words descendant and child, the main point to remember is that all children elements are also descendants but not all descendants elements are direct children. They are either grandchildren or great grand children.
The Child Combinator (>) only selects those HTML Elements that are direct children of a specified element.
While the Descendant Combinator selects all HTML Elements that are either children, grandchildren, great grandchildren and so on. They all are descendants of a specified element and thus all are selected.
Which one to Use
If you only want to target or select direct children of an element, you should use Child Combinator, if you want to select all direct and indirect children of HTML element, you should use Descendant Combinator.
Example
In the example below, the first paragraph element is child of first div, while second paragraph element is child of second div. But both paragraph elements are descendants of first div.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Difference Between Descendant Selector and Child Selector</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id='first'>
<p>This Paragraph is Child of Div with id='first'.</p>
<div id='second'>
<p>This Paragraph is a Child of Div with id='second' but it is not a Child of Div with id='first', instead it is Descendant of that div.</p>
</div>
</div>
</body>
</html>
Consider this second example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Difference Between Descendant Selector and Child Selector</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<p>This is Paragraph 1.</p>
<div>
<p>This is Paragraph 2.</p>
</div>
</section>
</body>
</html>
In above example, to target first paragraph, we will use child combinator (>) with section element selector.
section > p {
color:red;
}
While to select both paragraph elements, we will use Descendant Combinator (space).
section p {
color:red;
}
Demo
Video Tutorial
Watch video tutorial on Difference Between Descendant Selector and Child Selector.