CSS Descendant Selectors

What is Descendant Selectors :

  1. Descendant : Element having child , grandchild elements.
  2. Descendant Selector : Style is applied to the element based on the whether element have sub element or not.

Live Example Snippet :

<div class="wrapper" id="main">
    <p>Learning Programming is Fun !!!</p>
        <caption>Programming and Creator</caption>
                <td>Dennis Ritchie</td>
                <td>James Gosling</td>
    <a href="http://www.c4learn.com">Home</a>

Explanation of HTML Code :

Child Parent
<h2>, <p>, <a> and <table>
<caption> , <tbody>
<th> , <td>

We can say that h2,p,a,table are the elements having parent as ‘div‘ and caption,tbody are the child elements of the table and grandchild of ‘div
Suppose we have written following style –

div.wrapper h2 {
    font-size: 18px;
    margin-top: 0;

then –

  1. Above style will be applied to element “H2” type heading only if “H2” is child of “div” element having class name “wrapper“.
  2. Suppose h2 is child of div element other than “wrapper” then above style will not be applied to that element.

Above rule will be applied to following HTML Only –

<div class="wrapper">
   <h2>Sample Heading H2</h2>