The descendant selector is used to select those elements which are inside of a given parent. To select the descendants of a parent, we put a white space between the parent and the descendant. For example, div p
, ul li
.
So, for example, if you use div p
, it will select each and every <p> element which is inside of the <div>. It means that these paragraphs either can be the direct child of the div or can be the nested child of the div element.
See the below example for clarification:
Example:
div p{ background: yellow; padding: 5px; }
The child selector on the other hand selects only those elements which are the direct child of a given parent. Like the descendant selector, it does not select the nested children. They remain unaffected.
See the following example for clarification:
Example:
div > p{ background: yellow; padding: 5px; }
Conclusion
The main difference between the descendant and the child selector is that the descendant selector selects all the elements which are inside of a given parent, doesn’t matter if they are the direct child or the nested child.
The child selector on the other hand selects only those elements which are the direct children of the parent. The nested child elements remain unaffected.
Thanks for reading.