VOOZH about

URL: https://www.geeksforgeeks.org/css/css-child-vs-descendant-selectors/

⇱ CSS Child vs Descendant selectors - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSS Child vs Descendant selectors

Last Updated : 24 Sep, 2024

In CSS, child and descendant selectors are used for targeting elements based on their hierarchical relationships in the HTML structure. These selectors allow you to apply styles with precision and control. This article will help you understand the differences between these two selectors and provide examples of how to use them effectively.

Child Selector(>)

The child selector (element > element) is used to select elements that are direct children of a specified element. This means that only elements immediately nested inside the parent element are selected.

Syntax: 

element > element {
 // CSS Property
}

Example: Match all <p> elements that are child of only <div> element. 

Output:

👁 Image
elements

Descendant Selector (Space)

The descendant selector (element element) targets all descendant elements, including children, grandchildren, and further nested elements, of a specified element. This selector matches any element that is a descendant, not just direct children.

Syntax: 

element element {
 // CSS Property
}

Example: It selects all the <h2> elements which are child elements of <div>. 

Output:👁 Image
Child and descendant selectors are used in CSS that allow you to target elements based on their relationships within the HTML document structure. The child selector (>) applies styles only to direct children of an element, while the descendant selector (space) targets all elements nested within a specified ancestor.

Comment
Article Tags: