Wednesday, May 1, 2002

Keep lookin’ good with Cascading Style Sheets

PROGRAMMING POWER

By Andrew Stuart

In my previous article, "Cascading Style Sheets make you look good," at http://www.dominopower.com/issues/issue200204/cascade001.html, we made a start on getting to know CSS (Cascading Style Sheets). This time, we'll continue this discussion by taking a look at both "embedded" Cascading Style Sheets and "linked" Cascading Style Sheets.

Previously, by using the STYLE attribute we were able to control the appearance of individual HTML page elements without using any Javascript or other code. Using the STYLE attribute means that you're including the specific style properties and values into the actual HTML tags themselves. This is called "inline" cascading style sheets.

Inline CSS is useful and quick, and it's great for fine-tuning the appearance of specific individual page elements. On the downside, it can be repetitive and difficult to maintain, and all those CSS properties can make your HTML code messy and difficult to understand at a glance. The other problem with inline CSS is that making changes often means going through all your code and finding all the places that you've used the STYLE attribute and editing them individually. Inline CSS doesn't facilitate global changes.

Embedded CSS is more flexible than inline CSS. Embedded CSS allows you to define a set of CSS "rules" which can be used throughout the HTML page. The CSS rules are gathered together into a single place--in between a pair of <STYLE> tags located inside the <HEAD> block at the start of the page.

Here's an example of an embedded style sheet:

<head>
<style>
 .myrule                &#123
        font: 23px Verdana, Geneva, Arial, Helvetica, sans-serif;
        color : green;
font-weight:bold }
 #anotherrule   {
font: 10pt Arial, Helvetica, sans-serif;
        color : black;
font-weight:italic }

</style>
</head>

<p class='myrule'>the first test</p>
<p id='anotherrule'>another test</p>

Rule structure

In order to understand Cascading Style Sheets, you need to understand CSS rules and the structure of those rules. The above example contains two rules, contained within the &lt;STYLE&gt; tags. Each rule starts with a &quot;selector&quot;. The selectors in this example are named &quot;myrule&quot; and &quot;anotherrule&quot;.

After the selector comes as many specific style declarations and values as you choose, separated by semicolons. A final curly bracket completes the rule.

You can include as many rules as you want in between the &lt;STYLE&gt; tags.