Cascading Style Sheets/Pattern
Introducing the (X)HTML Document Tree
editThe document hierarchy of an (X)HTML document can be likened to a family tree. This can be seen if we take a look at a basic example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <body> <div id="title"> <img /> <p> </p> </div> </body> </html>
If we present the above example in a different way, the relationships and hierarchy of the elements becomes immediately apparent.
html | body | div /\ / \ img p
In describing the tree/hierarchy in this example we can say that the body
element is a child of the html
element, just as div
is a child of body
and img
and p
are both children of div
and siblings to each other. html
is the ancestor of div
as div
is indirectly descended from html
.
Targeting Elements within the Hierarchy
editSuppose we were to create a rule such as p {color:blue;}
. This would cause each paragraph throughout the document to be in blue. However, if we want to be a bit more "picky" about which elements are affected we can define the context under which this rule gets applied. If only paragraphs within div
elements should be in blue the rule needs to be div p {color:blue;}
. Now, say that only paragraphs in one div
element, defined by a certain ID are to be blue. We could then refine our target region by having div#title p {color:blue;}
.