The CSS Descendant Selector

How do we specify an descendant selector?

  • As Html elements are based on a tree structure where elements can have sub-elements, etc., we can also specify a descendant element within another element as a selector. This is called a descendant selector.
    div p {color:red; font-size:12px; line-height:15px;}

    Only p elements inside a DIV element will be affected by this rule.
  • The p element need not to be a direct child of the div element, but for instance a child of the blockquote element which is a child of the div element.
    Example of a descendant selector:
    <html>
      <head>
        <style type="text/css">
          p {color:red;}
          div p { font-size:16pt; color:blue;}
          p em {color:green}
          /* the last will write all em elements inside a paragraph to be green*/
        </style>
      </head>
      <body>
        <p>This paragraph is written in a red color</p>
        <p>Using <span>the <em>em element</em>  in the p elements</span> causes the text
          within the em element in this case printed <em>with green color</em> </p>
        <div>
          Text inside the div tag follow all preset defaults.
          <p>paragraph inside div element is blue and 16 pt.</p>
         <blockquote>
          <p>Using the <em>em element</em>  in the p elements causes the text
            within the em element in this case printed <em>with green color</em> </p>
         </blockquote>
        </div>
      </body>
    </html>


© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.