Cascading Style Sheets in Two Minutes

The preceding approach to styling web pages has a few downsides.

First, you need to explicitly state the attributes of each page element. When you want to change the look of the page, you need to go through the source code line by line and change every instance of every attribute. This may be okay with a few simple pages, but as the amount of content increases, the pages become more difficult to maintain. Additionally, the attributes applied to HTML elements allow only limited scope for you to adjust how they are displayed.

Wouldn't it be better to make one change to the code and have that change applied to all HTML elements of a given type? As I'm sure you've already guessed, you can.

To achieve this goal you use styles. Styles may be embedded within your HTML document by using style tags in the head of the document:

<style type="text/css">
    ... style definition statements ...
</style>

 

Alternatively, they may be linked from an external file, using a link element, once again placed in the head section of the document:

<link rel=stylesheet href="mystylesheet.css" type="text/css" />

 

Tip

 

You can even define styles on-the-fly. These are known as inline styles and can be applied to individual HTML elements. Taking the body tag of Listing 2.2 as an example:

<body bgcolor="#cccccc">

You could achieve the same effect using an inline style:

<body style="background-color:#cccccc">

 

 

 

Setting Style Sheet Rules

Style sheets allow you to set styling rules for the various HTML elements. A rule has two components: the selector, which identifies which HTML tag the rule should affect, and the declaration, which contains your styling rule. The following example defines a style for the paragraph element, <p>:

P {color: #333333}

 

This example determines that any text enclosed in paragraph tags <p> ... </p> should be displayed using dark gray text. You may also specify more than one rule for each tag. Suppose that, in addition to gray text, you want all text in the paragraph element to be displayed in italics:

P {color: #333333; font-style: italic}

 

A style sheet can contain as many such rules as you require.

You may also apply a declaration to more than one tag at once, by separating the tag selectors with commas. The following rule determines that all h1, h2, and h3 headings appear in blue text:

H1, H2, H3 {color: blue}