:web design/

A short look at CSS

HTML is not supposed to be used to define the appearance of a Web page. That statement might seem surprising if you are looking at web authoring for the first time, but this is the position of the W3C, which sets the standards (or, at least, the nearest thing the web has to standards). This is why putting any HTML 4 page which uses the <font> tag through a validator will (or should) give at the very least a warning that that element should no longer be used.

According to the standards, HTML (actually, the current standard is XHTML, but let’s stick with HTML for the moment) is there to provide a logical structure to a document, not define its appearance. The manner in which the document is displayed should be controlled using style sheets. This division requires designers to think about the organisation of a page, rather than its layout.

If you look at a good HTML text, or examine the information on the W3C site, you will find that the HTML elements which are presentational — <font>, <center>, etc. — are deprecated, i.e. should no longer be used. Tables should not be used for layout. Every aspect of a page’s appearance — positioning of page elements, font faces, sizes and styles, background images, etc. — should be set using cascading style sheets (CSS).

There are two enormous problems with this: the first is that only version 4 and higher browsers support CSS; the second is that CSS support is variable and idiosyncratic even in those browser versions which support it. Netscape 4.x browsers are particularly problematic. Nevertheless, CSS is important because it is the future of Web design, and because, even when restricted to areas with little cross-browser incompatibility, it is incredibly powerful.

The power of CSS

Consider, for instance, the way in which text formatting had to be handled in HTML 3.2. If text was in a table, a <font> tag had to be applied to the text in every table cell. This is time-consuming, fiddly, and does not make for easily readable code, but it was the only way to ensure text within tables had the desired appearance.

With CSS, life is much easier. All that is required is to define a style for table cells like so:

td {font-family: Verdana, Arial, Sans-serif;
    color: #660066}

This will produce a uniform style of text for every table cell in the document. It’s getting a bit ahead of ourselves, but it serves to illustrate the power and convenience of CSS.

The example should also illustrate that CSS is in no respect a replacement for HTML. In fact, it is closely tied to HTML because it is to the HTML elements that the style rules are applied.

Using CSS in a document

There are three ways to incorporate style information in a document; they are not exclusive, and indeed all three methods can be used in the same page:

  1. by linking to an external style sheet
  2. by embedding the style sheet in the document <head>
  3. by applying inline style information directly to the element concerned.

If more than one method is used, in any particular instance where there is conflicting style information, that nearest to the element concerned takes precedence: an inline style overrules an embedded style, which overrules a linked style. In other words, local style overrules global style.

Additionally, users may have a style sheet — IE 5 for the Mac, for example, allows users to specify a style sheet of their own for viewing Web documents. This may be useful to ensure text is a legible size and paragraphs are not excessively wide; such users’ style sheets would be overruled by the document creator’s style sheets (unless the user explicitly opts to override them).

This is is why the technology is called Cascading Style Sheets: there is a chain of precedence, with increasingly specific style information overruling more general style information.

Comparing the three methods

Each of the three methods of applying style information has its pros and cons:

  Pro Con
External

One style sheet can be used for many documents — efficient and time-saving.

The external style sheet requires extra download time, which in theory could slow page loading.

Embedded

Does not require any extra download time. Allows application of document-specific styles.

The style information must be reapplied in every document.

Inline

Does not require any extra download time. Provides very precise control of style — even down to the level of one character.

Note, though, that such precision of control can be achieved using embedded or external style sheets in combination with the SPAN element.

Must be applied to every instance of the style’s use and is very closely bound to the HTML — very time-consuming to update (no practical benefit over <font>).

Note that as the standards move to stricter XHTML, use of inline styles will be deprecated in favour of external style sheets.

Additionally, if Netscape 4 support is important, note that NN4 does not handle inline styles well, and if CSS positioning (v.i.) is used the presence of any inline styles may destroy the layout.


In practice, loading of an external style sheet causes little noticeable delay in page rendering, unless you have a particularly slow Internet connection. Certainly the increased load time is not normally long enough to outweigh the convenience of using a global stylesheet for a site as compared with applying the same styles to every document — and being faced with changing the style information in every Web page when the site is modified.

It should be obvious that using inline styles would be every bit as cumbersome as using the <font> tag — every application of every style would have to be applied to every element. Nevertheless, there are instances when inline style is appropriate, and in particular there is one use which we shall come to later where it is almost the norm.

The sensible approach to using these methods should be apparent:

  1. Define global styles for your site (or a section of it) using an external style sheet.
  2. Where some documents require modifications to the styles, apply them using a style sheet embedded in the document
    <head>.
  3. For occasional unique instances, use of inline styles may be appropriate.

Now we shall look at the basics of how to apply CSS rules to Web pages.

External style sheets

External style sheets are simply plain text files containing the style information. They are named using the extension .css and linked to the document like so:

<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" 
href="stylesheet.css">
</head>
<body>
    content
</body>
<html>

In addition to rel, type and href, the <link> element in this context has a media attribute that indicates to which medium (or media) the style rules in the style sheet should apply. Thus media="screen" defines the rules as applying to display on a monitor, while media="screen,print" would also apply the rules to printouts.

However, media is part of the CSS2 specification; most browsers are not even compliant with CSS1. In particular, Netscape 4 browsers will ignore every piece of style information if anything other than media="screen" is used.

Defining styles

There are three basic ways of defining styles within the style sheet: directly defining the style of HTML elements, or using classes and ID values. The element, class or ID value is the selector, and to the selectors are bound style properties such as font-size; this will be given a value such as 16px.

Rules for writing style sheets are not identical to those for writing HTML, although there are similarities. Most of the time, style sheets are case-insensitive, but two important exceptions are the names of font families and URLs, which are outside the scope of the CSS syntax. Here is an example of a style rule for the <p> element:

p {font-family: Times, "Times New Roman", Serif;
   font-size: 1em;
   color: #000000;
   text-align: justify;}

The selector in this case is simply the HTML element p, written without the angle brackets used in HTML markup. The properties and values to be applied to it are enclosed within curly brackets.

Some properties can have several possible values separated by commas, as with the font-family property above; if the font Times is present, it will be used; if not, then if Times New Roman is present that will be used; if that is not present, then the browser’s default serif font will be used.

CSS properties do not need to be enclosed within quotes unless the value concerned contains spaces, as with Times New Roman. If there is more than one property defined for a selector, the properties are separated by semicolons. Note that, as with HTML, properties are spelled in the American fashion — “color” and not “colour”.

If similar rules are to be applied to a number of elements, this can be done at the same time with different rules then applied to the individual items:

p, h1, h2 {font-family: Verdana, Arial, Helvetica, 
Sans-serif;
    color: #000000;
    width: 28em;}

p {font-size: 1em;}

h1 {font-size: 2em;
    font-weight: bold;
    text-align: center}

h2 {font-size: 1.4em;
    font-weight: bold}

Additionally, rules can be specified for the instance of one element occurring within another:

p, h1, td {font-family: Verdana, Arial, Helvetica, 
Sans-serif;
    color: #000000}

p b {color: #FF0000} 

td b {color: #0000FF}

This means that <b> will produce bold, red text within paragraphs but bold, blue text within table cells. This sort of thing may be useful, but so far the techniques are very general, applying to every occurence of an HTML element. The full flexibility of CSS only becomes apparent when we look at classes and IDs.

Using class and ID

Both classes and ID values allow the application of style rules to a subgroup of HTML elements. Within the Web page, they are applied to elements like so:

<p class="main">…</p>
<p id="note">…</p>

One crucial difference that must be understood between the use of classes and ID is that each ID value must be unique within the document, but many elements can be of the same class — in fact, the elements do not even have to be of the same type. Let us consider a style rule like the following:

p {font-family: Times, "Times New Roman", Serif;
   font-size: 1em;
   color: #000000;}

This will produce black text in a serif font at the browser’s default setting for font size. This may be perfect for the bulk of the text on our page, but suppose there is some of the text on the page which needs to be formatted differently.

Specifically, let’s assume we have two or three paragraphs which we want to be rendered in boldface and coloured red, and also that there is one paragraph, a note about copyright, which we want to be rendered in a smaller, sans-serif font.

Since the red paragraphs will be using the same rules, the appropriate way to handle that problem is using classes; since the copyright paragraph is unique, it is reasonable to use ID to define its style. The styles would be defined like so:

p {font-family: Times, "Times New Roman", Serif;
   font-size: 1em;
   color: #000000;}

.red {font-weight: bold;
   color: #FF0000;}

#copyright {font-family: Arial, Verdana, Helvetica, 
Sans-serif;
   font-size: .85em;}

As you can see, when the selector is a class, this is indicated by an initial full stop, when it is an ID value there is an initial hash mark.

The copyright ID can only be used once in the document, but class="red" can be used wherever it is appropriate (that is, in any element which can contain text). There is no reason why any of the following could not be used:

<h1 class="red"></h1>

<td class="red"></td>

<div class="red"></div>

<strong class="red"></strong>

<i class="red"></i>

You should note that when you are applying style rules using either class or ID to an element which already has style rules applied to it, there is no need to re-apply any properties which are not being changed: in the above example, <p class="red"> will still produce serif text at the default size, and <p id="copyright"> will still give black text.

Note that it would be preferable to give the classes a name related to function rather than appearance. I used class="red" purely to demonstrate the technique, but in practice it would be better to, say, call it "important" or "specialnote" — this makes it easier to read the stylesheet for one thing, and it also makes it easier to produce, for example, an aural stylesheet, where the notion of red text is meaningless, some time later.

Embedded style sheets

Using a style sheet embedded in the document is, as far as writing the style rules and applying them to the HTML, exactly the same as using an external style sheet. The difference is that instead of using the <link> element, we use <style>. If our style sheet were to consist of the above example, this is how it would be embedded in a document:

<html>
<head>
<title></title>
<style type="text/css">

p {font-family: Times, "Times New Roman", Serif;
   font-size: 1em;
   color: #000000;}

.red {font-weight: bold;
   color: #FF0000;}

#copyright {font-family: Arial, Verdana, Helvetica, 
Sans-serif;
   font-size: .85em;}

</style>
</head>
<body>
</body>
</html>

Again, the <style> element should support the media attribute.

Imported Style Sheets

Another theoretical method of incorporating style sheets in a document is importing them using this type of markup:

<head>
<title></title>
<style type="text/css">

@import url(stylesheet.css);

</style>
</head>

The one real plus to this technique is that it allows the importing of multiple stylesheets, including some which can be selected by the user as alternatives to the stylesheet specified by the designer; it would also bring together the link to an external style sheet and document-specific rules embedded in the document (which must come after the @import command or commands), rather than having to use both <link> and <style> tags. Unfortunately, few browsers support this method.

Note: This has now changed, with most recent browsers supporting the @import method; in fact, this is a good way to hide complex stylesheets from Netscape 4 which does not support it.

Inline style

If one wished, it would be possible to apply all the style rules directly to each specific element — that would, however, be a very time-consuming and inefficient way to do it. To illustrate the technique, here is the copyright paragraph tag written using inline style:

<p style="font-family: Arial, Helvetica, Sans-serif;
color: #000000 font-size:.85em">
</p>

The one area where inline style is often used is in CSS positioning, which we will take a look at later. Note, though, that the W3C advocates moving away from inline styles to the use of external stylesheets — separating content and presentation.

Again we should emphasise the fact the these three techniques are not exclusive, and it is entirely legitimate to combine them: that is, really, part of the point of Cascading Style Sheets.

What about older browsers?

We have already stated that you need a version 4 or higher browser to get any benefit from style sheets. (True, Microsoft IE 3 did have some sort of CSS support — but it was very poorly implemented.) What about people who do not use such a browser?

The first thing to note before answering that question is that the vast majority of people accessing the Internet, to judge from browser statistics, do use a browser with at least some CSS support. Certainly, we are talking about more than 90%, possibly more than 95%.

However, there are still people using Netscape 2, Netscape 3 and IE 3 as well as the numerous other browsers which are available. What happens when they load a page which uses CSS?

When a browser encounters HTML it doesn’t understand, it ignores it; in an HTML tag, any attributes not recognised are ignored. So if Netscape 3 loads a page which uses CSS, it will ignore the style information and render the page using its default rendering of the tags. Clearly, this is not going to be aesthetically as pleasing as the page looks in a more advanced browser, but it should be recognisable as a version of your page.

In other words, CSS degrades gracefully — if it is not supported, the absence of it does not impede access to the page. The situation is not so comfortable, though, with one of the major uses of style sheets: CSS positioning.

CSS Positioning

Many Web pages use tables to control the alignment of the page contents. Until recently there was no alternative. The only choices were: no layout, with text filling the screen width and the page contents arranged top to bottom, or use tables to control, more or less, the placement of the page elements. This use of tables is heavily frowned upon, and for some good reasons. As well as tying layout tightly to the HTML, it can cause problems for text-only browsers like Lynx.

But it works.

However, CSS technology brings with it the capability of precisely positioning page elements.

The first move in this direction was made by Netscape and didn’t involve CSS at all: with their version 4 browsers Netscape introduced the <layer> tag. This defined a box in the screen which could contain other page elements (text, images, etc.) and which could be precisely positioned. The <layer> tag, though, was never adopted by anyone else, it was never accepted as part of the HTML standard and, with their version 6 browsers, Netscape will be dumping the <layer> tag.

However, CSS-Positioning, usually in connection with the <div> element, gives precisely the same functionality as did the <layer> tag. In theory, CSS-Positioning could be applied to almost any tag, but using it with anything other than <div> can produce unpredictable results, especially in Netscape.

Because the functionality is basically the same, I tend here to refer to CSS-Positioned <div> tags as “layers”, because it is shorter and there is rarely a circumstance in which we would want to discuss the Netscape proprietary tag.

The style information to position a layer is incorporated like so, if you choose to use inline styles:

<div id="Nav2" style="position:absolute; left:7px; 
top:339px; width:81px; height:260px; z-index:12; 
overflow: visible; visibility: visible">…</div>

Or in a stylesheet:

#Nav2 {
	position: absolute;
	left: 7px;
	top: 339px;
	width: 81px;
	height: 260px;
	z-index: 12;
	overflow: visible;
	visibility: visible;
		}

This defines the layer’s position in relation to the top of the page, the left edge of the page, the layer’s height and width, what to do with content which is too large for the defined area, whether or not the layer is visible, and its z-index. The z-index is a number indicating how the layer relates in a notional three-dimensional space to other layers on the page. Layers with higher z-index values are “on top” of layers with lower z-index values. If the z-index is not defined by the author, positioned elements will be assigned a z-index value depending on where they occur in the document: the later in the document, the higher the z-index.

Note that the layer has a defined id value; even if inline styles are used, you may want to give it an id to allow JavaScript to manipulate the layer — either to change its visibility or to move it around the screen.

Since each layer needs its position defined independently, there may be no great advantage to placing the style information in an embedded sheet, and indeed clarity might be enhanced through having the style information present in the <div> tag. Of course, in a large site with a uniform page layout throughout the site there may be great advantage in placing the positioning style information in a global stylesheet.

However, we have be be very clear that pages built using CSS-Positioning generally do not degrade well. Load such a page into Netscape 3, and everything seems to be jumbled all over the place. CSS-Positioning is very attractive, but if you wish to include users of browsers which do not support CSS in your site’s visitors you have three options.

You can design a site which will work in as many browsers as possible, perhaps using tables to control layout; design pages for CSS-supporting browsers and pages for older browsers — a multiplication of workload which may not be worthwhile; or design pages for version CSS-supporting browsers only. This does not necessarily mean that you ignore the users of other browsers: you can design even a site which uses CSS-P to be at least usable, if not aethetically perfect, when CSS support is absent.

Things to beware!

There are some problems with using CSS, many of which relate to variability in browser implementation of the technology. Some particular points to be careful of:

Summary

CSS gives an unprecedented level of control over the appearance of Web pages, but unfortunately only in version 4+ browsers. Most browsers do not fully implement the CSS standards, so results can be unpredictable; Netscape 4.x tends to be the most problematic. CSS degrades well and older browsers can still display the page contents in a usable manner. This means that CSS can be used without shutting out users of older browsers. As browser compatibility with the standards improves, the level of control, and the ease with which it can be applied, will improve enormously.

On the other hand, CSS positioning does not degrade well, but does provide precise control over the positioning of page elements and combined with JavaScript allows manipulation of the elements’ position and visibility. As older browsers fall out of use, it is probable that CSS-Positioning will be the standard way to control page layout.

More on this…

Further reading:


Site Meter
Valid XHTML 1.0!Valid CSS!Level Triple-A conformance with WAI guidelines