Cascading Style Sheets (CSS)

Cascading Style Sheets allow authors to control the presentation of their documents; they apply typographic styles and spacing instructions to elements on a page. The word cascading refers to what happens when several different sources of style information are provided - style information is passed down from higher-level style sheets until overridden by a style command with more weight. This Chapter only covers CSS Level 1.

There are a number of sources on style sheets. Apart from the web itself (try http://www.google.com/ as a starting point), there is Meyer's Cascading Style Sheets: The Definitive Guide [Meyer 2000], Deitel, Deitel & Nieto's massive tome Internet and World Wide Web - How to Program [Deitel 2000] (Chapter 14), Musciano & Kennedy's HTML & XHTML: The Definitive Guide [Musciano 2000] (Chapter 8), Niederst's Web Design in a Nutshell [Niederst 1999], (Chapter 23) and Spainhour & Eckstein's Webmaster in a Nutshell [Spainhour 1999] (Chapter 9).

Style Elements

A style is simply a rule that tells the browser how to render a particular element. A rule defines a specific value with one or more properties of an element. For example, most elements have a color (note the spelling :-) property which specifies which colour is used to render the contents of the element.

In-line Styles

The simplest way to specify a style - include a style attribute with a tag specifying the properties and their values. Consider Figure 1.

<H1 style="color: red;">A Red Heading</H1>


Figure 1 : A Red Heading

The semicolon is redundent here; it is used to separate properties when there is more than one.

Document-level Style Sheets

Include a <style> element within the <head> element of a document to affect all elements within that document, except for those with in-line styles. Consider Figure 2.

<HEAD>
<STYLE type="text/css">
H1 {
	color: red;
	font: italic;
}
</STYLE>
...
</HEAD>
<BODY>
<H1>A Red Italic Heading</H1>
...
<H1>And Another</H1>
...

Figure 2 : A Red Italic Heading

The type attribute defines the type of style being included (strictly the MIME type). Cascading style sheets are of type text/css; Javascript style sheets are of type text/javascript; etc.

In this example, H1 is called the selector, The curly brace-delimited text is called the declaration, color and font are properties, and red and italic are values. Multiple values for one property are separated by white space.

External Style Sheets

Include a <link> tag within the <head> element of a document to import an "external" style sheet into the document. An external style sheet is a separate file and can be re-used to influence a collection of documents. For example, this document (and all the other networking documents) have the <head> element illustrated in Figure 3.

<HEAD>
...
<LINK href="../networks.css"
      rel="stylesheet"
      type="text/css">
...
</HEAD>

Figure 3 : Networks Style Sheet

The rel attribute specifies the relationship between the current document, e.g. this one, and the associated document, in this case the file networks.css in the parent directory. Note that the external style sheet can be located anywhere on the web!

Style Syntax

Comments in style sheets are the same as those in the C programming language, namely everything from /* up to and including */, as illustrated in Figure 4.

H1 {
        color: red; /* Red Top-level Heading */
}
...
/************************ 
 * Green Italic         *
 * Second-level Heading *
 ************************/
H2 {
        color: green;
	font: italic;
}

Figure 4 : Comment Styles

Note that comments cannot be nested.

Basic Selectors

As mentioned above, a style rule consists of a selector, followed by a curly brace enclosed, semicolon-separated list of property:value pairs. Some properties require that multiple values are separated with commas, as illustrated in Figure 5.

P {
        font-family: Arial, "New Courier", sans-serif;
}

Figure 5 : Font Selection

The browser will use the first font that it has loaded from the list, that is why a generic font (sans-serif) is the last option. Note that the second option is enclosed in quotes because the name contains a space. Current style-conscious browsers are case insensitive.

Multiple Selectors

Elements separated by commas in a selector list are all affected by the property style values in the rule, as illustrated in Figure 6.

H1, H2, H3, H4, H5, H6 {
        background: yellow;
	color: purple;
	text-align: center;
}

Figure 6 : Vivid Headings

All headings will have purple text on a yellow background and centred horizontally. This is clearly shorter than repeating the same property values for each heading individually.

Contextual Selectors

Elements separated by white space constitute a contextual selector, as illustrated in Figure 7.

OL LI       { list-style: decimal; }
OL OL LI    { list-style: lower-alpha; }
OL OL OL LI { list-style: lower-roman; }

Figure 7 : Nested Ordered List Styles

With these styles, the first-level list items are numbered in decimal, the second-level list items are numbered with lower-case letters, and the third-level list items are numbered with lower-case roman numbers, as shown here. If there is a potential ambiguity between two contextual styles, the more specific context wins, as illustrated in Figure 8.

P EM    { color: red; }
P UL EM { color: blue; }

Figure 8 : Coloured Emphasis

In this example emphasised text within a paragraph will be coloured red, but emphasised text within an unordered list, within a paragraph, will be coloured blue.

Style Classes

It is possible to create different styles for the same elements, where each is distinguished by a class name. The style is applied by naming it as the value of the class attribute in the corresponding tag.

Regular Classes

In a book or technical paper, you might want to define specific styles for different parts. Figure 9 is the style sheet used for this and the other networking documents.

/* Style Sheet for Networks course
 *
 * 0.0.0 Initial implementation (mick, 22 Sep 2000)
 * 0.1.0 Add book hierarchy (mick, 5 Oct 2000)
 * 0.2.0 Add figure hierarchy (mick, 22 Nov 2000)
 * 0.2.1 Re-organise class structure (mick, 8 Dec 2000)
 *
 */
/*
 * Book > Part > Chapter > Section > Paragraph
 */	
.book H1, .book H2 {
	text-align: center;
}
.part H1, .part H2 {
	text-align: center;
}
.chapter H1, .chapter H2 {
	text-align: center;
}
/*
 * Figure
 */
.figure {
	text-align: center;
}
.figure TABLE {
	background: white;
	margin-left: auto;
	margin-right: auto;
}


Figure 9 : Networking Style Sheet

This style sheet is loosely structured on the DocBook markup from Walsh & Meullner's book [Walsh 1999]. Thus a book consists of a number of parts, each containing a number of chapters, etc. Note that class names cannot be nested.

Generic Classes

A generic class is simply a name without an associated tag and makes it easy to apply a style to a range of elements, as illustrated in Figure 10.

.standout {
        background: yellow;
        color: green;
	font-style: italic;
}

Figure 10 : Standout Class

Any element using this class, e.g. <P class="standout"> or <TABLE class="standout">, will have italic green text on a yellow background.

ID Classes

An ID class is similar to other classes except that the name, i.e. the id attribute, has to be unique within the document. This identifier can be the target of a URL, used by automatic document processing tools, or used to specify a style rule. It uses a # character before the class name instead of a period. Consider Figure 11.

#purple { color: purple; }
H1#blue { color: blue; }

Figure 11 : Bad Language

This allows us to have just one blue-coloured top-level heading, <H1 id="blue">, and one other tag in purple. Not exactly the most useful of features.

Style Properties

There are five distinct kinds of property values.

Font Properties

The following group of properties affects the way text is displayed, both in terms of font and spacing.

font
Shorthand property for specifying a list of values in one rule.
font-family
family name
font-size
absolute size|larger|smaller|percentage
font-style
italic|normal|oblique
font-variant
normal|small-caps
font-weight
bold|bolder|lighter|normal|100|200|...|900

Background Properties

Background properties are applied to the "canvas" behind an element. Background colour appears behind the content and its padding, stopping at the border.

background
Shorthand property for specifying a list of values in one rule.
background-color
colour name|RGB value
background-image
URL|none
background-position
pos1 pos2 where pos1 is top|center|bottom|length|percentage and pos2 is left|center|right|length|percentage
background-repeat
no-repeat|repeat|repeat-x|repeat-y

Figure 12 illustrates how to place a watermark in the background without repeating it.

BODY {
        background-image: url(images/watermark.gif);
	background-position: center center;
	background-repeat: no-repeat;
}

Figure 12 : Central Watermark

Figure 13 illustrates how to place a ribbon down the left-hand side of the page.

BODY {
        background-image: url(images/ribbon.gif);
	background-position: top left;
	background-repeat: repeat-y;
}

Figure 13 : Left-hand Ribbon

Text Properties

Style sheets make a distinction between font properties, e.g. size, style, appearance, and text properties, e.g. alignment, presentation.

letter-spacing
normal|length
line-height
normal|length|percentage
text-align
center|justify|left|right
text-decoration
blink|line-through|none|overline|underline
text-indent
length|percentage
text-transform
capitalize|lowercase|none|uppercase
vertical-align
baseline|bottom|middle|sub|super|text-bottom|text-top|top|percentage
word-spacing
normal|length

Box Properties

The CSS model assumes that HTML elements always fit within a rectangular box. The core element is surrounded by three more boxes - the padding, the border, and the margin, as illustrated in Figure 14.

Box Model

Figure 14 : Box Model

A number of properties accept from one to four values. Figure 15 illustrates how they are applied.

Number of values Affected borders, margins, or padding
1 All items have the same value
2 First value sets top and bottom, second value sets left and right
3 First value sets top, second value sets left and right, third value sets bottom
4 First value sets top, second value sets right, third value sets bottom, fourth value sets left

Figure 15 : Multiple Effects
border
Shorthand property for specifying a list of values in one rule.
border-bottom, border-left, border-right, border-top
Shorthand property for specifying a list of values in one rule.
border-bottom-width, border-left-width, border-right-width, border-top-width
medium|thick|thin|length
border-color
colour name|RGB value
border-style
dashed|dotted|double|groove|inset|none|outset|ridge|solid
border-width
Shorthand property for specifying a list of values in one rule.

Figure 16 illustrates some of the potential border styles available, although some may not be rendered correctly. Try an alternative browser.

dashed dotted double groove
inset outset ridge solid

Figure 16 : Border Styles

Margins are very similar to borders, but with less attributes. Margins use the parent element's properties.

margin
Shorthand property for specifying a list of values in one rule.
margin-bottom, margin-left, margin-right, margin-top
auto|length|percentage

Padding is similar to margins. Padding uses the element's properties.

padding
Shorthand property for specifying a list of values in one rule.
padding-bottom, padding-left, padding-right, padding-top
length|percentage

There are a number of additional properties that specify how an element is presented.

clear
both|left|none|right
float
left|none|right
height
auto|length|percentage
width
auto|length|percentage

Naturally, many properties can be brought together. Consider Figure 17.

IMG {
        border: red 8px;
	float: left;
        height: auto;
	margin-left: 2in;
        width: 50%;
}

Figure 17 : Positioning an Image

Image widths will be scaled to 50% of the parent element's width, the height will be adjusted accordingly; the images will be on the left of the current text flow with a left-hand margin of two inches; the borders will be red and eight pixels wide.

This paragraph floats to the left and has a width of 25% of its parent's width; there is a solid border.

This paragraph floats to the right and has a width of 30% of its parent's width; there is a solid border.

This ordinary paragraph should flow around the paragraph on the left and the paragraph on the right. Of course, the actual behaviour will depend on the browser. It has no specific styles applied. Floating paragraphs, like these two, can be used to render asides, or even footnotes, on web documents. Floating images are also pleasing on the eye. For more detailed and fine-grained control over layout and positioning, it is necessary to resort to tables, where each cell is a rectangular element.

List Properties

List items are treated as a box preceded by some sort of marker, usually a bullet for an unordered list and a number or alphabetic character for an ordered list.

list-style
Shorthand property for specifying a list of values in one rule.
list-style-image
URL|none
list-style-position
inside|outside
list-style-type
circle|decimal|disc|lower-alpha|lower-roman|none|square|upper-alpha|upper-roman

Classification Properties

These properties tell the browser how to classify and handle various elements.

display
block|inline|list-item|none
white-space
normal|nowrap|pre

Tag-less Styles

Up to now, the Cascading Style Sheets have been used to modify the appearance of a complete element. In order to alter the appearance of only a portion of the element, usually text, we use the <span> element, as illustrated in Figure 18.

This example uses <SPAN style="text-decoration: line-through;"> to put a line through some text.

Figure 18 : Deleting Text

Applying Styles

Creating style sheets is an investment of time and energy that pays off in the long run. Designing a style sheet for a one- or two-page document is probably not time-effective, but for maintaining the look and feel of a complete web site it is certainly worth the effort.

The only down side is that support for style sheets is currently patchy and inconsistent between the major browsers.

Alternative style.

References

  1. [an error occurred while processing this directive]
  2. [an error occurred while processing this directive]
  3. [an error occurred while processing this directive]
  4. [an error occurred while processing this directive]
  5. [an error occurred while processing this directive]
  6. [an error occurred while processing this directive]