CSS from the Ground Up

by Joe Gillespie — Jan 1, 2004

Introduction

If you are frightened by the prospects of using Cascading Style Sheets, there's no need to be. Using a computer can be daunting for someone coming to it afresh but after a while, you think nothing of it. It all comes down to taking small steps to begin with and that's what I'm going to do in this series of tutorials. One step at a time!

Whether you normally use a WYSIWYG editor and stay clear of that source stuff in the background or even if you have never created a Web page at all, this tutorial will set you off in the right direction.

It assumes little or no knowledge of putting a Web page together. It really is 'from the ground up'.

What will you need?

Nothing special. If you have a Web page editor, fine. If not, you can use any text editor – NotePad on a PC or SimpleText or TextEdit on a Mac. If you are already using DreamWeaver or GoLive, we are going to be using 'source' mode.

Don't panic!

A graphics editor is not essential because I won't be worrying too much about graphics to begin with.

Oh, you will also need a browser, but that goes without saying. In fact, I'd recommend that you get a few different browsers. If you only have Explorer, you should also get Mozilla and any others from the list on the New Browsers list in this month's editorial.

If you want to upload your pages to a Web server, you will need some kind of FTP program but don't worry about that for the minute, you will doing everything here on your own computer.

Step One – A Basic Page

Before we can do anything, we need a basic Web page. Here is the most basic Web page possible.

<html><head></head><body> This is my Web page </body></html>

What we have here are three sets of 'tags' – tags usually come in pairs but not always.

Encompassing the whole page is the <html>...</html> tag pair. The first one <html> is the 'opening tag' and the 'end tag' is the same, except that it has a forward slash character between the < and the html>.

Inside the <html></html> tag are two more tag pairs.

<head>...</head> contains information that doesn't actually appear on your Web page, the most important probably being the page title that appears in your browser's title bar. You do this by enclosing the page title inside a title tag pair like this...

<html>
<head>
<title>My page</title>
</head>
<body>
This is my Web page content!
</body>
</html>

The <body>...</body> tag pair encloses all the content of your Web page, the text, images, Flash movies – whatever. You can type it into your text editor or into the 'source' window of a WYSIWYG editor – or you can copy and paste it from here.

HTMLephant

This is my HTMLephant. Yes, it's corny but at least you won't forget it!

So there is a Web page that will work fine in any browser – after you have saved it. Call it 'index.html' because that's the name for the first page on any Web site. You can save the file anywhere on your computer's hard disk, but to keep things neat and tidy, create a new folder to keep your Web pages in.

The normal way to open your page in the browser is to use the 'Open' item in the browser's 'File' menu but there's a quicker way. Make a shortcut or alias of your file and put it on the desktop. From there, you can just drag and drop the file icon into your browser window and it will show up in all its glory!

Your page should look like this »

Wonderful as it is, your Web page is missing a vital ingredient – content. There is little point in having a Web page if it doesn't actually say something (other than "This is my web page content!") but I'm going to leave that up to you.

Any content must go between the <body>...</body> tag pair so that the browser will display it.

Just poured into a naked Web page like this, text has no structure or style. By structure, I mean that the words just flow left to right, top to bottom words with no particular emphasis other than the order in which they appear. It makes more sense to group those words and sentences into paragraphs, headlines, subheadings – well, you know, the basic things you were taught at school.

Browsers ignore any line breaks or paragraphs you have in your raw text. They also ignore tabs and if you have more than one space between words, the extra ones are ignored too.

Almost any passage of text benefits from having a headline, a subhead, a few separate paragraphs and maybe a 'byline' at the bottom.

In HTML, the mechanism for doing this is provided by yet more 'markup' tags.

A paragraph is created by enclosing text within <p>...</p> tag pairs. In HTML, a paragraph is simply a block of one or more sentences with an extra bit of space to separate it from the next one – like the ones you see here.

For headlines, there are six different degrees of emphasis going from the largest <h1>...</h1> down to the smallest <h6>...</h6> They look something like this...

This is a h1 heading

This is a h2 heading

This is a h3 heading

This is a h4 heading

This is a h5 heading
This is a h6 heading

As you can see, they decrease in size as the number gets bigger with h4 being approximately the same size as this 'small' body text. h5 and h6 are smaller, but bold.

There are a few other tricks that we often play with text to give emphasis to words and phrases. Rather than thinking about how they look, consider their true functions.

Bold is a heavier version of the body text and denoted with <b>...</b> however, bold is a print style term and on the Web, it is preferable to use strong <strong>...</strong> Although they will look similar on your screen, HTML should work on other devices too. Software that reads Web pages to people with poor vision will understand strong and add the necessary stress.

Italics are produced with, you guessed it, <i>...</i> tags. Again, with HTML, it is better not to use this visual style but to use <em>...</em> This gives the functionality of italic type regardless of the device reproducing the text.

Underlining can be done with the <u>...</u> tag pair but underlining on a Web page has a special meaning. It usually indicates a link. It is best not to use underlining as a means of emphasis as it will confuse the readers.

The one other important tag is the line break <br /> Unlike the other tags, this one doesn't require an end tag, it wouldn't make much sense anyway, where would it go?

By using these basic markup tags, the text starts to take on some form. It becomes more like what you would produce with a word processor.

This basic page will probably look quite different in other browsers and computers. Every browser has its own default set of styles and unless you instruct the browser differently, it will use these defaults. To over-ride the default styles, we simply produce our own styles which are grouped together into a collective 'style sheet'.

Step 2 – A Style Sheet

A style sheet is a simple enough concept, it's a page of style definitions or specifications that instruct the browser how to display the various elements on a page. If you are wondering where the 'Cascading' comes-in, don't worry about it yet. I'll come back to that later when we start to apply styles to our HTML.

For simplicity, we are going to build our style sheet into our Web page. Later, you will find that you can have an 'external style sheet' in a separate file which can be called-upon by several pages and has the big advantage that you only have to make one change on this master style sheet to affect all the other pages that link to it.

The styles we are going to use are defined in the <head>...</head> part of our page like this...

<head>
<style media="all" title="mystyles" type="text/css">
<!--
-->
</style>
</head>

Here, you see a pair of <style>...</style> tags but there are a few more bits in there that need to be explained.

type="text/css" tells the browser that we are just using plain text to describe the styles, nothing fancy.

title="mystyles" is simply to identify the styles for your benefit.

media="all" is where it starts to get interesting. You can have a style sheet to describe how your page looks on a computer screen (media="screen") and another completely different one to format it for printing (media="print"). There are other media too such as 'projection', 'tv', 'braille' and 'aural'. Now you will appreciate the logic of not using 'bold' and 'italic'. For now, we'll just use 'all', which is general purpose.

The <!-- and --> characters are a way of hiding text on a Web page – you can only see it in the markup. This is called 'commenting' but as the styles are in the <head>...</head> section of the page, they shouldn't show up anyway.

The first thing we are going to define the style for the overall body of the page. Everything within the <body>...</body> tags will have this style, or set of styles applied to it.

The basic body style definition looks like this...

body { }

The word body followed by a pair of curly braces.

We will give the page a background colour...

Browsers default style usually give black text on a white page, but we will change that to a warm pale grey. This is how we give the body background colour a value. Note that we don't use an equals sign '=' but a colon ':'.

body { background-color: #e8eae8 }

What's all this #e8eae8 stuff?

Colours on Web pages are defined by mixing 256 shades of red, green and blue in various proportion. Humans have 10 digits on their hands, so they count in tens. Computers prefer to count in sixteens, not that they have fingers, but once you go over nine, there are no single numerals to represent 10, 11, 12, 13, 14, 15 so we substitute letters a, b, c, d, e , f. So, in 'hexidecimal' counting, 10 is represented by 'a' and 15 by 'f'. When you go above 15, you add a second digit and '10' represents 16. Using this method, all the numbers from 0 to 255 can be represented by two numbers or letters - 255 is ff. So, #ffffff would be white and #000000 black.

Our background colour is therefore red e8(232), green ea(234), blue e8(232). The hash sign at the front denotes that were are using hexideximal and not ordinary decimal numbers.

Sometimes you will see only three characters, for example, #2a0. This is shorthand for #22aa00. When there are two characters the same in each of the three colour values, you can dispense with the second and the browser will understand what is meant.

hexidecimal colours

Using only three digits, you can have 4096 different colours, with six digits there are over sixteen million.

red green and blue

With single digit colours, red, green and blue each have 16 steps of brightness that can be combined in many ways to produce all the others.

If you are hand-coding, using three digits colour values is simpler – and probably enough.

Anyway, let's now add a type colour to take the place of black. It was chosen with a colour picker tool in Photoshop so its a 6 digit hexidecimal number...

body { background-color: #e8eae8; color: #5d665b }

Note how the background-color and foreground (type) colour are separated by a semi-colon. Be careful not to mix up the colons and semicolons or things will go horribly wrong.

And now, so that the type doesn't run right up to the edges of our page, we can give the page a margin all round. 'margin: 50px' is added to our body style definition, again separated from the previous one by a semi-colon.

body { background-color: #e8eae8; color: #5d665b; margin: 50px }

Any type we now add to the page will be a dark grey/green on a pale grey background by default. We will see how this can be over-ridden for special cases later.

Have a look at what we've done so far »

Step 3 – Styling Text

Although we have rid our page of the stark black and white look and replaced it with a gentler feel, there's a lot more we can do. We can change the type face, the type size, the amount of space between lines and add other niceties such as paragraph indents.

The font style

We'll do the font style (typeface) first as that makes quite a dramatic difference. Unlike designing for print, Web pages can only use fonts that are installed on the reader's computer so we can't specify just any type we fancy, we have to use ones that are common to all computers – ones that come pre-installed with the system. That narrows the choice down quite considerably. You will find that you are limited to two or three serif faces, the same number of sans-serif faces and a monospaced, (typewriter) style. Instead of choosing only one font style, we specify a range in the hope that one of them will be installed on the reader's computer.

web fontsHere are some common fonts on Windows and Mac computers. You can't depend on any particular one being present so you have to provide alternatives.

Here is a typical sans-serif font family specification.

font-family: Verdana, Geneva, Arial, sans-serif;

This is a serif font family

font-family: Georgia, "Times New Roman", Times, serif;

Note that when a font name has more than one word, the whole thing has to be put inside quotation marks – "Times New Roman"

Let's add the sans-serif fonts to our styles and see what happens.

Our page set in sans-serif font »

The font size

Specifying a font size is a contentious issue. In print, you can specify a font size in points and the type will always be that size. It will always take up the same amount of page space and the line breaks will be exactly as you set them.

On the Web, font sizes are not set in stone and change from one computer to another, sometimes quite dramatically. Depending on the user's screen size, operating system and browser, type can go from unreadably small to kiddie's picture book large. Luckily, users are able to set a 'comfortable' size within their browser's preferences which narrows-down the size variations a little, but they can still be quite different from what you expect.

With the rising popularity of Wi-Fi and handheld devices, the browsing conditions for your pages will change dramatically in the next few years. To keep you pages futureproof you need to think in terms of liquid page designs that adapt themselves to the screen size.

Repeat after me, "The Web is not the same as print!"

Relative font sizes

If you want the widest possible audience for your pages, it is best to specify the font size relative to the user's chosen default size. There are various ways of specifying relative font sizes. You can use percentages of the default (%), or use can use a unit called an 'em', which is the same as 100%. 1.2 em is the same as 120%. The preferred way is to use a set of pre-defined descriptions that sound like T-shirt sizes. 'Medium' is the same as 100% or 1em. 'Smaller' is a size down from that and 'Larger' a size bigger. Then there is x-small, xx-small, x-large and xx-large. The advantage of using this system over percentages or ems is that the broswers won't allow the type to become too small to read. You could, for instance, specify a type size of 0.7 em or 70% and it would look fine on your PC. For somebody using a Mac with a smaller default font size, the 70% could take the type down below the size of legibility. xx-small is smart enough to know what the minimum size of type a computer can handle.

xx-large x-large large medium small x-small xx-small

xx-small type: This type is small but not too small to render.
This type is way too small: This type is way too small

Absolute font sizes

If you have a limited audience for your site that uses basically the same kind of computer setup as you do, you can also specify font sizes in pixels. Pixels don't vary greatly in size from one desktop computer to another so the type size will be similar, if not identical. Once you move to laptops and handhelds or to very large, high resolution monitors, pixel sizes do vary from the norm and the type sizes will change accordingly.

So that you can see the differences, I have set three paragraphs of text here using three methods – percentages, T-shirt sizes and pixels. On my screen in Mozilla, they are all very similar in size but might not be on yours.

This line is set at 85% of the size of the text around it.
This line is set as x-small
This line is set at 11px absolutely

Note that you should never use 'points' to specify font sizes for the screen, only for print.

The line spacing

The amount of space between lines is about 120% of the font-size by default. Adding a little extra generally improves legibility, especially if the lines are long. I'll discuss line length later. With our current page, the line length is determined by the width of the browser window, so it might well be longer than ideal.

To change line spacing, again we can opt for relative (% or ems) or absolute (px). In this example, I've set the line height, that's the height of the character plus the extra spacing above it to 180% of the font size (small) for the whole page. As the body style definition is getting a bit long, I've split it into multiple lines, the browser doesn't care but it makes it easier for humans to read. As long as the curly brackets are there and each style definition is separated by a semi-colon, that's fine.

body { background-color: #e8eae8;
color: #5d665b;
margin: 50px;
font-family: Verdana, Geneva, Arial, sans-serif;
font-size: small;
line-height: 180%
}

Now we have a page with more 'air' »

Paragraphs

Everything we've done so far affects all the text on the page. Now we will look at how we can narrow our style down to more specific areas.

As I mentioned earlier, large blocks of text can be broken up into paragraphs to make them easier to read. There are a number of ways to visually separate paragraphs from one another. You can add some extra space or maybe indent the first line.

In creative typography, designers will sometimes use other, less common techniques such as grossly indenting by half a column width or even exdenting (the opposite of indenting). CSS can handle all these but the default paragraph separator is a 'paragraph space' which is about half of the line-height.

To make a block of text into a paragraph, simply enclose it inside a <p>...</p> tag pair. To be able to manipulate the paragraph style with CSS, we add p { } to the style definitions in the page's head under the body styles. Inside the brackets, add text-indent: 3em

<style media="all" title="mystyles" type="text/css">
<!--
body { background-color: #e8eae8;
color: #5d665b;
margin: 50px;
font-family: Verdana, Geneva,
Arial, sans-serif;
font-size: small;
line-height: 180%
}
p { text-indent: 3em
}
-->
</style>

This page is broken up into paragraphs »

Note how the first paragraph is not indented – it is not enclosed in <p>...</p> so it is not officially a paragraph at all – in HTML terms.

Headings

I've already explained about the six levels of headings that you get by default in HTML. We are not stuck with those, we can redefine them to our own requirements. Again it's just a matter of adding more definitions to the styles.

Headings, by default are big and bold and have extra space above and below. Remember, headings from h1, h2 and h3 are bigger than normal text and h5 and h6 are smaller. Let's play with a h3 heading and change its colour and font.

h3 {color: #966b72; font-family: Georgia, "Times New Roman", Times, serif }

Now we have headings »

You might also notice that I've added a blank line above the second heading. If you just put an empty paragraph <p></p> it won't work, there has to be something inside the tags. Putting a blank space won't work either <p> </p> because HTML ignores spaces unless they are between characters. What we need is an invisible character and HTML provides one called a non-breaking space which can be typed-in as &nbsp; like so...

<p>&nbsp;</p>

The non-breaking space is also very useful to put between words that you don't want to split when the words wrap at the end of lines - things like people's or company names.

Extra tweaks

Before going on to the next part, let's try a few extra tricks with our page of text.

In the body definition, I set the margin to 50 pixels all round. We can have different margins for left, right, top and bottom. All we need to do is split them up like this:-

margin-top: 70px;
margin-left: 120px;
margin-right: 50px;
margin-bottom: 70px;

That gives something more like a printed page with a wider left-hand margin. I've also picked out a couple of words in bold (strong) and italic (em). Be warned that italic type can look bad on some computers and is especially hard to read at smaller sizes.

View our page with styled text »

Now, you have a page that has a bit of style about it – without too much effort. Nevertheless, it's still like a typewritten or word-processed page. In the next issue, we'll look at some more interesting layout possibilities.

Whilst you are waiting, you can play around with the values in the page you have just created. Try different font styles, sizes, line spacing but most importantly, look at your page in as many browsers as you can to see how different thay can be.

Step 4 – More text formatting

Before going any deeper into text formatting, it's a good idea to familiarise yourself with some basic typographic terms.

When we talk about type size, or font-size in CSS, it refers to the distance from the top of a capital letter such as 'A' to the bottom of a descending letter 'p' or 'y'. There might also be a small amount of extra space called 'leading. The word comes from the fact that printers used to put strips of lead (metal) between lines of type to give more line space.

Today, we don't use lead, we just say that there is so much line space between the base of one line of type and the next. Line space is therefore the height of the type plus this extra space. In CSS, we might say line-height: 180%; with the value sepecified as a percentage, ems or pixels (px). More about line spacing further down.

Vertical-align allows you to adjust the baseline of individual letters relative to the rest of the text but this is for fairly specialised use with mathematical formulae and we won't bother too much about it here. For this simple example, I could have used the <sup>2</sup> tags but with CSS, there's more control.

E=MC2

CSS also gives us control over horizontal spacing, the space between individual letters and words.

This is useful for adding visual style to headlines.

SPACED HEADLINE

letter-spacing: 0.5em; word-spacing: 0.5em

Designing for readability.

Before CSS was as well supported in browsers as it is now, there was one vital feature that was missing from HTML text formatting that even the most humble typewriter could handle – line spacing. When there is little or no space between lines of text, it becomes intimidating and difficult to read. The longer the lines become, the worse the problem gets.

Lines that are too
short cause
the eye's left to right
reading pattern
to be disrupted
too much.

Lines that are longer than ideal are also tiring and the beginning of the next line down becomes more difficult to locate.

For comfortable reading, a line of text should be about the same length as one and a half to two lower case alphabets – that means 40 to 60 characters or eight to ten words.

If lines get longer, more line space helps readability. Many early Web pages had text running all the way from the left side of the screen to the right, regardless of the screen size. Some still do – and screens have become wider too.

By default, there is a little line space in browser text settings. It's approximately 20% of the font size (cap height plus descender). With CSS you can have as much line space as you like. If you are using relative font sizes, you can specify it as a percentage of the font-size – font-size: 1em; line-height: 1.5em (the same as 150%). If you are using an absolute font sizes, you can specify something like font-size: 11px; line-height: 16px

The spec for this page is font-size: small; line-height: 180% which is roughly equivalent to one-and-a-half line spacing in a word processor or old fashioned typewriter.

To demonstrate, in this example the top of the page has no margins and the text has no line-height setting. The general specs for the body of the page provide the font family, the font size and the colours for the type and background only...

body {
color: #5d665b;
font-size: small;
font-family: Verdana, Geneva, Arial, sans-serif;
background-color: #e8eae8
}

The lower section the text is enclosed within a page division <div>...</div>, it's like a page within a page. It has a left margin of 250px and a right margin of 200px and the line-height is set to 180%. These styles are added to the general body specs by a process called 'inheritance'. Just as a child might inherit certain characteristics from its parents, which in turn, are then passed down to its children, some CSS styles 'cascade' when they are nested inside other styles.

<div style="margin-left: 250px; margin-right: 200px; line-height: 180%">...</div>

Page divisions 'divs' are a very important part of Cascading Style Sheets and we will look at them in more detail next month.

Contrast

Unlike a printed page that you read by reflected light, a page on a computer screen is luminous. The difference in brightness between black text and a white background is many magnitudes greater on a monitor than on a printed page.

Vast expanses of black text on a white background can be like walking in bright sunlight without sunglasses. Only in extreme cases would you shade your eyes to look into the distance outside, before that you will probably be squinting and feeling uncomfortable without realising quite why.

Reducing the contrast of Web page text makes for more comfortable, less stressful reading. If you go too far however, you start to make things difficult for people with poor vision.

In an article like this where there's a lot of text to read and the reader is likely to spend some time in front of their screen, it is important to make the experience as comfortable as possible, so I have used a gentle background tint and soft colours.

Step 5 – Lotsa lists

Another very useful formatting technique often used in documents is the 'list'. These are like paragraphs but have a little more going for them.

HTML provides for basic lists that either have bullets (unordered lists) <ul>...</ul> or numerals (ordered lists) <ol>...</ol> at the beginning of each list item <li>...</li> Each type has a few options that can be specified from HTML – <li type="square">...</li> gives a square bullet, <li type="i">...</li> gives lower case Roman numerals.

  • Unordered list item
  • Unordered list item
  • Unordered list item

Default unordered list

  • Unordered list item
  • Unordered list item
  • Unordered list item

Unordered list with square bullets

  1. Ordered list item 1
  2. Ordered list item 2
  3. Ordered list item 3

Default ordered list

  1. Ordered list item 1
  2. Ordered list item 2
  3. Ordered list item 3

Ordered list with roman numerals

CSS gives you more options and control – just add a definition for ol or ul to your styles.

ol {list-style-type: lower-roman; margin: 1em 0 1em 40px }

This does the same job as adding it to each list item in HTML and gives you control over the margins around the complete list. The four values 1em 0 1em 40px refer to top, right, bottom, left and can be ems, percentages or pixels.

If you want closer control of the individual list items, you can specify margins for those also – to get more line space, for instance...

ol li { margin: .5em 0 .5em 0 }

adds an extra half em of line space above and below each list item for an ordered list. For an unordered list you would substitute ul li.

Even better, you can use your own graphics for bullets.

ul { list-style-image: url(/images/smiley.gif) }
ul li { margin: 1em 0 1em 0}
  • You are going to like this
  • You will love this too
  • And what about this?

And, ultimately, a different bullet image for each list item...

<li style="margin: 1em 0pt; list-style-image: url('/images/icon1.gif')">We know about people</li> <li style="margin: 1em 0pt; list-style-image: url('/images/icon2.gif')">We know about images</li> <li style="margin: 1em 0pt; list-style-image: url('/images/icon3.gif')">We know about ideas</li> <li style="margin: 1em 0pt; list-style-image: url('/images/icon4.gif')">We know about writing</li>
  • We know about people
  • We know about images
  • We know about ideas
  • We know about writing

Styles defined in the head section are general to the whole page, that's not going to do what we want here. To apply styles to individual list items, it has to be done 'up close' or 'inline'. The definitions are inserted into the opening <li> HTML tags in the body of the page. Note however that IE6 (Windows) puts the icons very close to the text. I've added some extra space at the beginning of each line to compensate – like this...

We know about people.

Step 6 – Linking

The whole point about HTML is that HT (HyperText) bit. Links added to words, phrases or images on a page can be clicked upon to whisk you off to some other place. These other places are called 'anchors'. Just think of stationary ships in the great sea of the World Wide Web with a chain made from links going down to an anchor on the sea bed. anchorThe ships are anchored at specific locations and that makes them easier to locate than if they were adrift at sea.

Each page has at least one anchor on it. The default one is right at the top of the page but you can add more anchors to any part of a page that you would like to be able to jump to.

<a href="http://www.wpdfd.com/index.htm">This is a link to the top of my home page</a>

So, you have a pair of tags <a>...</a> plus an extra href="..." part included within the first tag. This is the hypertext reference address that you want to go to.

If you place an anchor on a page at a specific place – well, actually, it should be immediately above where you want to land up – it goes like this...

<a name="myanchor" title="myanchor"></a>

That's an <a></a> tag pair with, for example, name="myanchor" included in the opening tag. There's nothing between the two tags.

To jump to this location, you add an extra bit on the end of the link...

<a href="http://www.wpdfd.com/index.htm%20%3Cem%3E#myanchor%3C/em%3E">This is a link an anchor on my home page</a>

As you are aware, links on a page are indicated by making them visually different from the surrounding text. The default is to underline the link text and make it blue. When you click on a link, it provides visual feedback by changing its colour to red. When you later come back to that link, it has changed colour again, to purple, to show that it has already been visited. Everybody that has ever used a Web page gets the idea of these conventions very quickly.

The default presentation of hypertext links in HTML has three distinct states.

An unvisited link

An active (just clicked) link

A visited link

Note that the cursor changes too. The default arrow pointer changes to a pointing finger when it passes over a link.

Of course, being 'designers' we are not content with the default look of links. Underlined text may be practical, but it can look ugly. The key requirement is that a link looks sufficiently different from the surrounding text to show that it's something special. Context is an important factor here too. Some text is obviously a 'menu' of choices whether it is underlined or not. Its prominence and position on the page and the fact that the words are inviting you to go somewhere else all give clues to its function.

Similarly, when a word or phrase within a block of text looks different, it must be for a good reason. The reason could be to add emphasis but again, it's the context that gives the clue and also the fact that other similar words or phrases have the same, consistent look. It wouldn't work if every link was a different colour.

CSS allows us to play around with how links look. Links don't have to be underlined, they don't have to be blue. All we have to do is set up a definition for 'a' – anchors.

a:link { color: #696; text-decoration: none }

As this page has a colour scheme other than black and white, I have changed the link colours to ones other than the default blue/purple. text-decoration:none gets rid of the underline.

If you want a visited link to be a different colour, you do this...

a:visited { color: #699; text-decoration: none }

CSS also allows an additional 'state' called 'hover'. This changes the colour of the text as the mouse pointer passes over it and gives a very useful extra clue that it is a hypertext link.

a:hover { color: #c93; text-decoration: underline }

There's that traditional underline coming in if you want it, but only temporarily whilst the pointer is hovering over the text.

The 'active' state of a link is what you see when you actually click on a link. Usually, it changes colour and some browsers also put a box around the text too.

css link states

To set up link styles that apply to the whole page, you would put something like this inside the style definitions in the head of your page.

 a:link { color: #696; text-decoration: none; background-color: transparent }
a:visited { color: #699; text-decoration: none; background-color: transparent }
a:hover { color: #c93; text-decoration: underline; background-color: transparent }
a:active { color: #900; text-decoration: underline; background-color: transparent }

The order of the style definitions is important here. Usually, the order doesn't matter in CSS definitions but here it is important that the a:hover and a:active definitions come last or they might not work.

Now, here's another state not officially sanctioned in CSS.

This is a dead link. It does nothing. If you have a link on a page that links to the same page, well, it doesn't make much sense that you can click on it and end up back where you started. It's like a signpost bending round and pointing at itself.

There are two ways to handle this. You can turn the link into what is effectively a heading by making it more prominent than the rest or you can make it almost, but not quite, invisible to indicate that it is not a valid selection. That's called 'greying out' and you will be familiar with the principle from other programs on your computer.

Why have it there at all if it's not a choice you want people to make?

Well, one of the most important principles of interface design is that you try to keep everything as consistent as possible. If you remove a menu item, for instance, some of the other ones will shift position. It is less confusing to the user if interface items stay nailed-down to the same spot.

The other element we have at our disposal here is the background colour behind the text. Sometimes designers change the text background to give an effect like a highlight marker for the hover and/or active states.

highlighted hover

There's a lot more that you can do with CSS links, we have only scratched the surface here but it should be enough you get you started. This example page demonstrates the principles that you learned here.

Step 7 – CSS Boxes

We've already seen that the text on a Web page can be broken up into headlines and paragraphs and that these mechanisms are already catered for in HTML. We have also seen how the default styles can be modified to suit our own tastes by providing them with new style definitions that over-ride the defaults. Now, I'm going to look at how you can make your own style definitions that extend the capabilities of HTML and make more interesting layouts.

The body of a page is the entire visible area but, as I showed in Step 3, we can break that up into smaller divisions that have their own styles. These divisions can be as small as a single character or larger, rectangular chunks of the page. All we have to do, is surround the area we want to style with a pair of tags <div>...</div> Those divisions are each like a mini page and are often referred to as CSS boxes. CSS Boxes are the fundamental building blocks for building Web page layouts and I'm going to spend some time explaining how they work because it is so important.

CSS boxes can have a width and height, a background colour or even a background image which can be made to repeat to give a pattern. By default, a CSS box goes from the left margin to the right margin of the page body. If you haven't specified a body margin, it will be the full width of the browser window. If you don't specify a height for a CSS box, it will have none. If you put some text into it, it will expand vertically to accommodate that text – or image.

To keep text away from the edge of a box, you can add padding...

padding

You have to be very careful with padding because it works quite differently in Microsoft Internet Explorer from all other browsers. Unlike the diagram here, IE puts the padding inside the box, so its width and height stay the same. All other browsers put the padding outside the box, adding to its width and height. So your box size will change depending on which browser is viewing your page and this can have quite disasterous results if you are depending on precise pixel measurements.

Beyond the padding, you can have a border...

borders

Borders come in a variety of styles and you can address each of the four sides separately in terms of thickness, style and colour. They look slightly different in the various browsers but here is what they look like in Mozilla...

border styles

The thickness of your border increases the box size accordingly.

To separate boxes from one another, you can give them margins.

margins

Margins and padding are often confused especially as what we normally call a 'page margin' in a book or web page is really 'padding' because it can't go outside the page – it is obviously inside. Just remember that this is a 'special' case. For the body of a Web page, the margin goes from the edges inwards, all other CSS margins go outwards.

Absolute positioning

In addition to having a height and width, CSS boxes can be put at any fixed position on a page by specifying position: absolute; Absolute positioning is easy to understand, that's how things usually work in real life. Your house could be 50 metres from North Street and 100 metres from East Street, for instance.

The most common way to give a box a position is simply to specify something like top:50px; left:100px but it doesn't have to be top and left, it can also be top and right, bottom and left or bottom and right.

Here are a few CSS boxes with different styles, each with its style definition displayed. The possible combinations are endless.

When boxes are positioned at absolute co-ordinates with definite widths and heights, it's very like sticking newspaper clippings and photographs into a page in a scrapbook. The problem is that scrapbooks always remain the same size – Web pages don't.

Relative positioning

If you wanted to describe the position of your next door neighbour's house, you could say that it was 70 metres from North Street and 100 metres from East Street, or you could say that it is 5 metres along from your house. Relative positioning assumes that CSS boxes are next to another one. The first box is the top one, the next one is below it and the next, below that. They effectively float downwards from the top of the page. This is something that rarely happens in real life but can you image being in a covered-over swimming pool with a pile of air mattresses. One would float to the top, the next would float up and get stuck beneath the one above it – and so on.

To get CSS boxes to sit beside one another rather than one below the other, you have to tell them to float: left; or float: right; Like the air mattresses in a wide swimming pool, they will sit side by side, where there is enough space. Then they will wrap around onto a lower level. You have to try and avoid that situation by making sure that the total widths of all your boxes in a line are not more than the page width. You can do this by specifying the width in pixels – but keeping the total below the minimum width of a browser. Or you can use percentages – making sure that the total percentages add-up to 100 – or preferably, slightly less. With relative positioning like this, avoid mixing pixels and percentages or results will be unpredictable.

The example of floating boxes here show the behaviour of relatively positioned boxes in single and multiple columns.

Step 8 – Custom Divs

IDs

When you are creating CSS boxes with custom definitions, there are no existing HTML elements to attach them to. You have to invent your own.

As there will probably be several or even many CSS boxes on any page, they have to be given names. We do that by giving them an 'identity' – id for short. An id uniquely identifies a CSS box on your page both to you and the browser so that it knows how to display it.

A simple example is where you divide a page into three horizontal areas. A 'header' at the top carries a logo and the navigational links. The middle bit contains the text and pictures. Down at the bottom, you might also have a 'footer' that gives a copyright notice and, maybe, echoes the navigation from the top.

This example actually has five horizontal boxes, the extra ones are for the navigation bar and the logo and sit between the header and text area.

simple layout

Note that the right columm is narrower than the one on the left to compensate visually for the extra space created by the ragged right hand side of the text – otherwsie the text would look off-centred.

In the style definitions, we stick a hash sign # in front of the name we want to give the box making them into 'identities'.

#header {...}
#navbar {...}
#logo {...}
#midsection {...}
#footer {...}

Then we have to tie the definitions to the actual CSS boxes by just referring to their ids like this...

<div id="header">...</div>
<div id="navbar">...</div>
<div id="logo">...</div>
<div id="midsection">...</div>
<div id="footer">...</div>

If we have already specified the type in the body declaration, then our boxes will 'inherit' those styles. Any style definitions that you add to the boxes' definitions will take precedence over the more general body definition. This is what 'cascading' is all about.

Classes

Sometimes you will want to use the same box several times on a page. Suppose you wanted to break-up the midsection into two or more separate boxes. In this instance we need a 'reusable' box instead of a unique one. A reusable box is called a class. Just as you have 'classes' of flowers or insects, a class is basically the same box but with different content. To show that we want a reusable class instead of a unique id, we use a period . instead of the hash sign.

.midsection {} can now be used as many times as we like and on the div itself, we put ...

<div class="midsection">...</div>
<div class="midsection">...</div>
<div class="midsection">...</div>

Span

Classes (but not IDs) can be applied at a text level. If we just want to pick out a few words in red, we can create a special class, let's call it .redtext

.redtext { #c00 } <span style="color: #cc0000">This is red text!</span>

Instead of wrapping the text we want in red in a <div>...</div>, we use <span>...</span> This is referred to as inline as it applies to a span of text that is inside another <div>...</div>

Use <span>...</span> any time you want to make a variation to some text that differs from the overall specification. It could be colour, font-family, size, weight or whatever.

So, in CSS, there are block elements which are rectangular boxes that can be unique 'ids' or reusable 'classes'. We also have inline elements that can address text at a character level.

Now we are starting to get somewhere!

Step 9 – All together now

Anything but the simplest Web page will use a mixture of ids and classes and possibly a combination of absolute and relative positioning. Going back to our simple, five section page from Step Eight, you might want to have multiple columns in the midsection. This involves using the float property, and I'll use float:left to keep things simple.

A left column is typically used for menus on many Web pages which means that it can be fairly narrow.

.leftcol {}

The middle column is the main text.

.midcol {}

And over on the right, we'll put another narrow column for reference links or advertising.

.rightcol {}

All three columns are specified as percentages so that they are fluid and adjust to the page width.

Notice that I'm using classes for these columns as I might want to reuse them further down the page.

This example replaces the single .midsection with three floated left columns.

<div class="leftcol">...</div><div class="midcol"...</div><div class="rightcol"...</div>

This opens-up a lot more interesting layout possibilities.

Don't leave any divs completely empty, even they are only 'white space'. Put a non-breaking space &nbsp; inside them.

Step 10 – Getting it right

Doctypes and validation

We are up to lesson ten of CSS from the Ground Up and I have a confession to make. Everything I have shown you so far - the markup, the example pages are all wrong! Well, they will probably work just fine unless you are using an ancient browser but if you test them with a syntax checker or put them through some sort of validation program, they will not pass.

What is a validation program you might ask?

You will be familiar with the concept of a spelling checker. There's probably one in your word processing program. It compares the words you have typed-in to a list of words in its built-in dictionary and alerts you if it can't find a match. It might be that the word isn't in its dictionary but it's also possible that you have misspelled it. In the more sophisticated word processors, your writing can also be checked for proper use of grammar and if you type a sentence that doesn't have a verb in it or too much repetition of the word 'and', it will nag you incessantly.

Before a spelling or grammar checker can do its job, it needs to know what language you are using. My UK English spelling checker is quite different from a US English spell checker - and what if you aren't using English at all?

Just as your English, or whatever language you write in, is checked for correctness, your HTML and CSS can, and should, be checked too. If you make a mistake in your English, people will probably recognise it as a typo, but understand what you mean, there's no real damage done. A tiny slip-up in HTML or CSS, on the other hand, is a different story. Something as seemingly insignificant as a comma or quotation mark out of place, can make all the difference between a page working or not - it depends on the particular error and the browser that's trying to make sense of it. It is a good idea to 'spell check' your HTML and CSS with a 'syntax checker' or 'validator'.

One of the main benefits of having a decent HTML editor is that syntax checking will be built-in as part of the package. You just don't get them with simple, general purpose text editors. If you have a HTML editor like HomeSite or BBEdit or a WYSIWYG editor such as Dreamweaver or GoLive, you will be able to check your markup for errors and hopefully get suggestions on how to fix it. If you don't have such a program, you can use the online validators provided by the W3C – W3C HTML ValidatorW3C CSS Validator – where you simply upload your files and get an immediate report back with a blow-by-blow list of errors – or not!

Of course, the checking program has to first know which 'language' you are using for your markup – there are several 'flavours' of HTML. So far, all the examples I've shown are written in HTML 4.01 – that's the current version and the most ubiquitous. But, there are sub-versions of HTML 4.01 – 'Strict', 'Transitional' and 'Frame Set'.

Strict is a very tightly defined set of rules as to what you can and can't do with your HTML.

Transitional is a little more forgiving and allows for some 'legacy' HTML and browser peculiarities.

Frame Set isn't used very much these days. We haven't looked at 'frames' in this series as they have pretty much gone out of favour since CSS came along.

Most people are happy to use 'Transitional' because it gives them a bit of leaway, but there are those who like everything 'by the book' and prefer to use 'Strict'.

To tell the browser what markup language you are using, and which flavour, put a DocType declaration right at the top of the page - above the first <html> tag. It looks like this...

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

I won't analyse all the stuff that's going on in there at this point, suffice it to say that with this mumbo jumbo at the top of your page, the syntax checker or validator will be able to do its work properly. It now knows which standards you are working to and can make judgements accordingly.

Having added a DocType, I can check pages in my HTML editor's syntax checker and be confident that they are squeaky clean. With that little side issue out of the way, we can go back to 'styling'.

Step 11 – External Style Sheets

So far, all the styles I've used have been built-into the <body>...</body> section of the pages. That way, it is easy to look at the source code of the page and see what's going on. It's all together in one place. However, it's very seldom that individual pages are done in isolation, it's much more likely that there will be a collection of pages with a common look in a Web site.

Instead of putting the style declarations on each and every page of a site, it's a much better idea to have just one style sheet and get all the individual pages to refer to that. It also means that if you want to change the background colour of every page on your site, or to use a different font face or size, you only have to change the 'master' style sheet. In fact, you can totally change the look of an entire site by making a few alterations to just one file.

Have a look at http://www.csszengarden.com/ to see this principle in action. Various designers have provided their own style sheets for the same basic page content and demonstrate admirably how the same skeleton can be given different 'skins' that completely change the character. To use an external style sheet, all we have to do is provide a link like this:-

<link rel="stylesheet" href="basicsstyles.css" type="text/css" media="screen">

This tells the browser to look for the style specifications in a file called 'basicsstyles.css'. It is a plain text file – type="text/css" and the styles are optimised for display on a computer screen – media="screen".

Style sheets are not limited to computer screen displays, you can produce style sheets for other media, like print, projection or even braille. When you think about it, a sheet of printer paper is not at all the same size or shape as a screen and nobody is going to want to waste their precious ink-jet ink on large areas of solid colour when all they want is black and white text for reference. A style sheet for a printer needs to make the page narrow enough for a sheet of paper, and unlike the screen style sheet, type sizes should be specified in points (pt). Colour schemes should be simplified, or abandoned completely. Then, all you have to do is add a second link in the <head> section just after the one for screen.

<link rel="stylesheet" href="printstyles.css" type="text/css" media="print">

If you are content to use the same style sheet for screen and print, then you can use this link...

<link rel="stylesheet" href="styles.css" type="text/css" media="all">

Although most of my style sheets are made external eventually, I usually start off with an internal style sheet at the initial design stages. When I'm happy with the look, I copy and paste the styles into a new file and replace them with a link.

Continue to Steps 12 - 15

Del.icio.us Digg Technorati Blinklist Furl reddit Design Float