CSS Child vs Descendant selectors
Child Selector: Child Selector is used to match all the elements which are child of a specified element. It gives the relation between two elements. The element > element selector selects those elements which are the children of specific parent. The operand on the left side of > is the parent and the operand on the right is the children element.
Syntax:
element > element {
// CSS Property
}
Example: Match all <h2> element that are child of only <div> element.
<!DOCTYPE html> <html> <head> <title> CSS child Selector </title> <style> div > p { color:white; background: green; padding:2px; } </style> </head> <body style = "text-align: center;"> <div> <h2 style = "color:green;"> CSS Child Selector </h2> <p> A computer science portal for geeks. </p> </div> <p>Geeks Classes is a quick course to cover algorithms questions.</p> <p>This paragraph will not be styled.</p> </body> </html> |
Output:

Descendant selector: Descendant selector is used to select all the elements which are child of the element (not a specific element). It select the elements inside the elements i.e it combines two selectors such that elements matched by the second selector are selected if they have an ancestor element matching the first selector.
Syntax:
element element {
// CSS Property
}
Example: It selects all the h2 element which are child element of div.
<!DOCTYPE html> <html> <head> <title> CSS Descendant Selector </title> <style> div h2 { font-size:26px; } </style> </head> <body style = "text-align:center;"> <div> <h2 style = "color:green;" > GeeksForGeeks </h2> <div> <h2>GeeksForGeeks</h2> </div> </div> <p> GeeksforGeeks in green color is example of child Selector <br>other GeekforGeeks is example of descendant Selector </p> </body> </html> |
Output:

Recommended Posts:
- jQuery | parent descendant Selector
- CSS | Syntax and Selectors
- Advanced Selectors in CSS
- JQuery | Multiple ID selectors
- CSS | Selectors Complete Reference
- Wildcard Selectors (*, ^ and $) in CSS for classes
- Which characters are valid in CSS class names/selectors?
- CSS | :nth-child() Selector
- CSS | :last-child Selector
- CSS | :nth-last-child() Selector
- How to use a not:first-child selector in CSS?
- CSS | :first-child Selector
- CSS | :only-child Selector
- jQuery | :nth-last-child() Selector
- jQuery | :nth-child() Selector
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



