Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

CSS Child vs Descendant selectors

  • Difficulty Level : Basic
  • Last Updated : 20 Feb, 2019

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:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :