Saturday, March 1, 2008

CSS Selectors, Part I

This is one of the big things that in my opinion, separates the CSS beginner from the intermediate.

CSS Basics

CSS (Cascading Style Sheets) starts with the word "Cascading" for a reason. You have external stylesheet files that apply to multiple pages, internal inline stylesheets for page specific rules, and tag level style rules. Each level will override all outer levels (so a tag level style attribute will override rules set in the header, or in an external file).

Selectors

Now, when defining a style rule for a tag, you give it the tag name, followed by brace brackets ({ }), in which you define what attributes you want. So, something like this:

a { color: Red; font-weight: bold; }

tells the browser that for all <a> tags, make the colour red, and the font bold.

Now, what if you want most of your <a> tags to be red and bold, but there are five navigation links you want to be a nice maroon? Based on what we talked about earlier, the obvious choice is something like this:

<head>
<
title>CSS Pwnz J00!!</title>
<
style type="text/css">
a {
color: Red;
font-weight: bold;
}
</style>
</
head>
...
<a href="index.html" style="color: Maroon">Home</a>

What the rules in the header tell the browser is that all <a> tags are to be red and bold, what the style attribute in the link tells the browser is that for this tag (and its children), make the colour maroon. These two directives are in conflict, so the one that is at the innermost level wins, the result being

home

... Which is a marooned, bolded link.

This is where most peoples knowledge seems to end. You can achieve the effect desired with these skills alone. There is alot more to the story though if one wants to write elegant code. One of the prime principals to keep in mind when writing elegant solutions is something called "Separation of Concern". But that will have to wait for part II.

No comments: