Tree Structures and Inheritance

Tree Structures and Inheritance

From Chapter 1, recall the discussion about HTML representing a document with a tree-like structure and how elements in HTML have children and parents. There are many reasons for having tree-structured documents. For style sheets, there is one excellent reason: inheritance. HTML elements inherit traits from their parents, just like children do. Instead of inheriting genes and money, HTML elements inherit stylistic properties.

Let's start by looking at the sample document:


  <title>Bach's home page</title>


    <h1>Bach's home page</h1>

    <p>Johann Sebastian Bach was a

      <strong>prolific</strong> composer. Among his

        works are:


      <li>the Goldberg Variations

      <li>the Brandenburg Concertos

      <li>the Christmas Oratorio




Figure shows the tree structure of this document.

6. The tree structure of a simple document.

Through inheritance, CSS property values that are set on one element are transferred down the tree to its descendants. For example, until now, our examples have set the font style to italic for H1 and H2 elements. Now, say you want to set all the text in the document to be italic. You can do this by listing all the element types in the selector:

<style type="text/css">

  h1, h2, p, li { font-style: italic }


However, most HTML documents are more complex than our sample document, and your style sheet would soon become lengthy. There is a better and shorter way to do this. Instead of setting the style on each element type, set it on their common ancestor, the BODY element:

<style type="text/css">

  body { font-style: italic }


Because other elements inherit properties from the BODY element, they all inherit the the font style (see Figure).

7. The result of inheritance.

As previously mentioned, inheritance is a transport vehicle that distributes stylistic properties to an element's descendants. Because the BODY element is a common ancestor for all visible elements, BODY is a convenient selector when you want to set stylistic rules for an entire document.

     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows