Style Sheets

Introduction

Cascading Style Sheets (CSS) are used to add styles such as fonts, colours and page layouts to web documents. The philosophy behind CSS is to separate content from presentation. The content is written in a markup language such as HTML and the presentation in CSS. Elements are styled with rules and the rule syntax is defined so that rules can be written for groups of elements in a compact manner. This grouping, along with inheritance of styles from parent container elements to their children reduces complexity and avoids repetition. CSS allows different style sheets to be applied to the same markup for different purposes such as on screen and in print.

If you're unfamiliar with CSS, there are many books and online tutorials on the subject, such as the tutorials at HTML Dog[1]. This chapter focuses on how to save bandwidth by using CSS for all presentation and how to optimise your style sheets.

Before we start talking about using CSS to apply styles, it's worth bearing in mind that sometimes the simplest designs are the most effective. Using fonts and colours sparingly will give your site a clean, uncluttered look and cut down on style information.

Finally, it is worth noting that a small minority of older browsers will not process CSS correctly, or will not process compressed CSS files correctly if you have implemented this - see the chapter on compression for more details. It is always worth making sure that a site is still usable when the style sheet is not available, e.g. that it is still possible to access and navigate content, even if the site lacks elegance.

Use External Style Sheets Rather than Embedding CSS in the Page

Style rules can be written in three ways

  • Within style tags in HTML:
<style type="text/css">
#box {margin:0; padding:1em 0 0.5em 0;}
#tab_content form,
#tab_content input
{margin:0;padding:0;}
</style>
  • Via the style attribute:
<div style="padding:0.1em 0 0 0;height:1.5em;width:54em;">
  • Within an externally referenced style sheet:
<link rel='stylesheet' type='text/css' 
href='templates/aptivate/css/styles.css'/>

or

<style type="text/css" media="screen,projection">
@import url(css/screen.css);
</style>

In general, embedding CSS in pages should be avoided, as shown in the first two examples. Instead, an external style sheet should be used. If you include the same external, static style sheet file in each page, it will be cached by the web browser and need only be downloaded once. This also helps to apply a consistent style across a whole website with minimal effort.

The exception is when the total size of CSS on a page is very small. In this case, the bandwidth overhead and delay from an additional HTTP request to the server may outweigh the cost of repeating the CSS on every page load. When some pages include CSS that is not shared with other pages, the argument for this is stronger.

Reference Style Sheets in the Document HEAD

Style sheets should be referenced in the document HEAD for two reasons — firstly, in some situations, Internet Explorer may display a blank page until it has loaded the style sheet, meaning that users lose the chance to read progressively loaded content while the page is loading. Secondly, the page may have to be redrawn with the content information after it has been loaded.

Use Style Sheets for All Presentation Information

Replace Presentational HTML Elements

Instead of using font tags to surround every piece of text, these can be replaced with appropriate font rules in the style sheet for the containing elements. For example:

p {
font-family:Verdana,Arial,Helvetica,sans-serif;
font-size:1.5em;
}

This optimisation will be greatest on text-heavy websites where a single style sheet is shared by many pages.

Replace Tables Used for Layout

Presentation information includes page layout. Before CSS support became widespread in browsers, web developers worked around the limitations of the available web technologies by using HTML tables for layout, instead of their intended purpose of representing tabular data in a spreadsheet style. Unfortunately old habits die hard and this approach is still widely used on the web.

There are many reasons why CSS is preferable to tables for layout information. Positioning with CSS is generally more efficient, resulting in smaller pages and style sheets. CSS also allows the display order of page items to be specified, meaning that the most useful content can be presented faster.

Tables cannot display incrementally unless they have fixed width. This means that the user must wait for the entire table to load before any of the content is visible. This is especially bad if the whole page is formatted as a large table.

For an example of a simple page layout using CSS, the following code uses floating elements and margins to position the navigation on the right and the main body of text on the left, opposite to the order in which they appear in the HTML.

Here's the CSS:

.testnav { float: right; width: 6.4em; }
.testbody { margin-right: 7em; }

and here's the HTML:

<div class="testpage">
<div class="testnav">Navigation</div>
<div class="testbody">Lorem ipsum dolor sit amet...</div>
</div>

This displays the navigation after the content, on the right, even though the navigation appears first in the file and therefore loads quicker.

Navigation
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus feugiat, arcu id molestie laoreet, ante nisl interdum tellus, eget interdum orci orci non tellus. Quisque egestas vulputate orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam lacus. Phasellus eget metus...

Use Shortcuts

If you want the same style to be inherited by all elements and the style is heritable, apply it to the body element and it will propagate down:

body {
font-family: Arial, Helvetica, sans-serif;
}

This does not work for non-inherited styles, such as padding, border and margin.

Rules can be applied to groups of elements using selectors. The universal selector (*) matches any element name in the document:

* {
border-collapse:collapse;
font-family:'Trebuchet MS','Lucida Grande',Verdana,Arial,Sans-Serif;
margin:0;
padding:0;
}

There are many more selectors available, such as picking out elements by their parents and ancestors, their order in the page, their ID or their CSS class.

CSS contains a shorthand for optimising style rules. If the same rule is to be applied to several elements, they can be written as follows:

ul, ol {
margin: 0.5em 1em 1em 2em;
list-style: inside;
}

Colours can sometimes be abbreviated. For example

color:#ff0000;

can be written as:

color:#f00;

Multiple font rules can be changed. For example

font-size:1em;
font-style:normal;
font-family:Verdana, Arial, Helvetica, sans-serif;

can be reduced to:

font:normal 1em Verdana, Arial, Helvetica, sans-serif;

Similarly, border and margin rules can be expressed in one line:

border-width:thin;
border-style:solid black;

is equivalent to:

border:thin solid black;

and

margin-left:0;
margin-right:0;
margin-top:0.2em;
margin-bottom:0.1em;

can be abbreviated as follows:

margin:0.2em 0 0.1em;

With borders and margins, the default left border is the same as the right, the default bottom border is the same as the top and if only one value is specified then it applies to all four.

Remove Comments and White Space from the CSS

Comments and white space will increase legibility of style sheets for website developers but they will be ignored by the browser and take up bandwidth.

Use Media Types

If you want to specify different layouts for different media types - for example fixed units for print and relative units for screen, use a separate style sheet for each media type. The browser will then only download the sheet it requires.

<head>
...
<style type="text/css" media="screen,projection">
@import url(css/styles.css);
</style>
<style type="text/css" media="print">
@import url(css/print.css);
</style>
...
</head>

Combine CSS Files

If several style sheets are to be loaded into one page, it may be more economical to combine all style sheets into one large file. Over slow connections, each CSS file will add a few seconds to the page loading time due to the time taken for the browser to request the file and receive the response from the server. Browser-specific versions of CSS files should be replaced by a single, cross-browser compatible file.

Use Optimisation Tools

Optimisation tools can be used to strip comments and white space from style sheets as well as combine and abbreviate rules, as described in this chapter. At the time of writing, the following online tools are available. The tools are not infallible and will sometimes introduce bugs into the CSS, so it is worth testing the resulting CSS with your site and changing compressor if necessary. A comparison of these tools[2] against various sites by http://www.bloggingpro.com suggested that Icey's CSS Compressor and CleanCSS were the most reliable at the time of testing, and that Icey's CSS Compressor achieved the best compression.

Browser Compatibility

Historically, browsers' support for CSS has tended to lag behind the standard, and misinterpretations of the standard have led to inconsistencies. The implementation of CSS in legacy browsers such as Netscape 4 is particularly buggy, and can lead to pages not being displayed at all. If external style sheets are referenced using the @import directive, these will be ignored by legacy browsers, so this is one way around this issue. However, style sheets loaded using @import rather than the link tag will cause Internet Explorer to display a blank page while the style sheet loads instead of progressively displaying content. For maximum compatibility, use @import; for overall speed, use link.

The latest versions of mainstream browsers such as Internet Explorer and Firefox have different ways of interpreting CSS depending on whether they are operating in quirks or standards mode. In quirks mode browsers will try to render pages in a manner compatible with previous versions, by emulating their bugs. As the name suggests, standards mode is more compliant with web standards. We recommend that you develop your website to be viewed in standards mode. This is achieved by correctly setting the full doctype at the top of all your pages. For HTML 4.01 Strict this is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

By using standards mode your site will maintain a consistent look and feel across all standards-compliant browsers.

Summary

We recommend that styles sheets be used to reduce loading time by:

  • Using external style sheets in the Document HEAD to load CSS
  • Replacing font tags with CSS
  • Laying out pages using styled divs rather than tables
  • Combining CSS files
  • Optimising CSS using tools like Icey's CSS Compressor[3]

Footnotes

[#1] http://www.htmldog.com/

[#2] http://www.bloggingpro.com/archives/2006/08/17/css-optimization/

[#3] http://iceyboard.no-ip.org/projects/css_compressor