Horje
Difference Between Descendant and Child Selectors in CSS

The Descendant selector and child selector in CSS are both used to target specific elements within the document structure, but they differ in their level of specificity and targeting.

Descendant Selector

It uses a space to select all descendants of a particular ancestor. In the below example, It selects all matching elements, regardless of their depth in the hierarchy. It’s less specific and more broad-reaching.

Syntax:

/* Selecting all paragraphs inside a div */
div p {
/* styles */
}

Child Selector

It uses the > symbol to select direct children of a particular parent. In the below example It specifically selects elements that are direct children of the specified parent, excluding nested descendants.

Syntax:

/* Selecting only direct children paragraphs inside a div */
div > p {
/* styles */
}

Differences

  • Specificity: Child selectors are more specific than descendant selectors because they only target direct children.
  • Scope: Descendant selectors have a broader scope, affecting all matching descendants. Child selectors narrow the scope to direct children only.



Reffered: https://www.geeksforgeeks.org


CSS

Related
What is the Universal Selector? What is the Universal Selector?
How to set Outline Styling in CSS ? How to set Outline Styling in CSS ?
How to create a Full-Page Background with CSS ? How to create a Full-Page Background with CSS ?
How to change Background Gradient on Scroll ? How to change Background Gradient on Scroll ?
How to Toggle between Hiding and Showing an Element using JavaScript ? How to Toggle between Hiding and Showing an Element using JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14