Climbing down trees
Just in case anyone isn’t clear on this, I’m going to explain, in detail, how to descend the object tree with your CSS selectors. Let me know if I’ve skipped or glossed over any important details. Return any hand-waving in kind.
If you’re thinking WTF is an object tree?, you should know that I often just make up names. Hopefully in this case it proves descriptive.
I think of HTML as a tree: At the tree’s top is the <html> tag; Its descendants are all the tags nested within it.
<html>
<head>
<title>
example page
</title>
</head>
<body>
</body>
</html>
In the example above, the children of <html> are <head> and <body>. The <title> tag is not it’s child, but it’s grand-child – <title> is <head>’s child and a descendant of <html>.
If we think about it like this, then a webpage is described by a tree of objects.
In CSS we can start from anywhere in the tree, and descend by separating two selectors by a space.
Note: CSS will give priority to the most specific selector that applies to an object.
Say we’re building a website that has a main section, and a sidebar – our HTML might look something like this:
...
<div id="main_section">
<h1>main heading</h1>
<p>some text in the main section</p>
</div>
<div id="sidebar_section">
<h2>main heading</h2>
<p>some text in the side bar</p>
</div>
...
In many situations, we’d want the text to differ in style between sections:
#main_section, #main_section p, #main_section h1 {
color: #000;
}
#main, #main p {
font-size: 9pt;
}
#sidebar, #sidebar p, #sidebar h1 {
color: #999;
font-size: 7pt;
}
#sidebar h1 {
font-weight: bold;
}
What we’re saying here is:
- any text in the main section, and any paragraph tags, or h1s that are its descendants should be black.
- any text in the main section, and any paragraphs that descend from it should be 9pt in size
- any text in the sidebar, as well as any paragraph or h1 tags that descend from it should be grey and 7pt
- any h1s who descend from sidebar should be bold
Note: #sidebar refers to an object whose id is sidebar (ex: <div id=”sidebar”>)
Note: Use commas to list all selectors you wish your CSS block to be applied to:
#sidebar p {
font-size: 7pt;
}
#sidebar h1 {
font-size: 7pt;
}is functionally equivalent to
#sidebar p, #sidebar h1 {
font-size: 7pt;
}
By using this technique one can make strategic use of classes and ids, rather than adding them to every object one wishes to style – making the HTML even cleaner.
I’m not sure what else to say, so hopefully I’ve helped to clear things up or at least confused the issue. If anyone has any specific examples they think would be helpful, let me know and I’ll add them?
Uncategorized, being helpful to people less experienced than myself in the ways of the world; mostly in the ways of the web actually