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">
    <h2>Heading</h2>
    <p>Learning Programming is Fun !!!</p>
    <table>
        <caption>Programming and Creator</caption>
        <tbody>
            <tr>
                <th>C</th>
                <td>Dennis Ritchie</td>
            </tr>
            <tr>
                <th>Java</th>
                <td>James Gosling</td>
            </tr>
        </tbody>
    </table>
    <a href="http://www.c4learn.com">Home</a>
</div>

Explanation of HTML Code :

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

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>
</div>