Saturday, March 28, 2009

CSS Basics – Part 4

This will be the final part of a series of articles which introduced the basics of Cascading Style Sheets (CSS). In this one, we will take a look at what makes up a style sheet. One might think that this is something that we should have looked at the very beginning of an article series for CSS basics. However, I took a different approach here in first explaining the why before looking at what.

First a quick reminder; part 1 was about how CSS got its name, part 2 covered its use in separating content from presentation and part 3 was about how the separated presentation (i.e. style) is hooked up with content with the use of selectors.

A style sheet is nothing more than a collection of rules. Each rule has a name (or selector to be precise) and a declaration block. A declaration block is a collection of declarations enclosed within a pair of braces (i.e. “{}” ), where each declaration consists of a property name, followed by a colon, followed by one or more comma separated values. Each declaration in a rule should be separated with a semicolon.

If the above sounds complicated, take a look at the following figure, which illustrates the anatomy of a CSS rule. What is shown on top there is an exploded view of a rule marked with Label (1). This exploded view highlights the important elements of a rule described above; i.e. the selector, the block delimited by opening and closing braces, the declarations and their constituent parts property name, colon, values and the semicolon.


You normally see rules as shown by Label (1). However, the whitespaces (i.e. tabs, spaces and line breaks) have no significance to the computer program (usually a browser) that processes these rules. Therefore, rules shown by Labels (2) and( 3) also have the same effect as the rule tagged as Label (1).

This format is technically referred to as the syntax of a CSS rule. Think of it as the grammar of a natural language, say English. To write proper English you must use its grammar correctly. Likewise, proper adherence to CSS syntax is a must. When you define a CSS rule, you have be very careful to put the braces, the colon and the semicolon in the required places. If you miss any or add more than what is required, your style sheet can go haywire and as a result you web page or blog can end up in a mess.

All right, this brings us to the end of this four part series covering the basics of Cascading Style Sheets in simple, non-technical English [as much as possible :)]. Hope you found it useful. For the more interested readers, I recommend the CSS Tutorial at W3Schools and the more comprehensive CSS Guide by Westciv.