CSS Child vs Descendant selectors
Child Selector: Child Selector is used to match all the elements which are children of a specified element. It gives the relation between two elements. The element > element selector selects those elements which are the children of the 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 <p> element that are child of only <div> element.
html
<!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 selects 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> elements which are child element of <div>.
html
<!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:
Please Login to comment...