Adding style with CSS

Over a decade ago, the <font> tag was created. Suddenly webmasters everywhere were able to change the colour, size and typeface of any text on their website.

Unfortunately there are some fundamental problems with the <font> tag:

CSS

Cascading Style Sheets (or CSS) were introduced in 1996 as a better way of styling your web pages. A style sheet is a separate document that simply contains a set of rules that define how your website should appear. Here is a simple example that shows how to make all top-level headings (<h1>) in your webpage appear green and twice as big as the main text of your webpage:

HTML document

<h1>How to write music</h1>
<p>To write music you will need a pen and some manuscript paper.</p>
…

CSS document

h1 {
	color: green;
	font-size: 200%;
}

Result

How to write music

To write music you will need a pen and some manuscript paper.

Using CSS with HTML

There are 2 ways to apply a style sheet to a web page. The first is to include the CSS code directly in the HTML document. This is done as follows:

<html>
<head>
<title>How to write music</title>
<style type="text/css">
h1 {
	color: green;
	font-size: 200%;
}
</style>
</head>
<body>
<h1>How to write music</h1>
<p>To write music you will need a pen and some manuscript paper.</p>
…
</body>
</html>

The preferred way is to have your style sheet in a completely separate document. This way, the single style sheet can be used by all pages in your website, so the style of all your pages can be changed just by editing the one CSS file. Suppose you name your style sheet “style.css”, this is how you would do it:

HTML document

<html>
<head>
<title>How to write music</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<h1>How to write music</h1>
<p>To write music you will need a pen and some manuscript paper.</p>
…
</body>
</html>

style.css

h1 {
	color: green;
	font-size: 200%;
}

A more advanced example

style.css

h1 {
	color: green;
	font-size: 200%;
	font-variant: small-caps;
	border-bottom: 1px solid green;
	margin-bottom: 0;
}
p {
	margin: 0.5em 1.5em 1em 1.5em;
}

Result

How to write music

To write music you will need a pen and some manuscript paper.

More than just font styles

CSS can do much, much more than styling text: you can use it to create the entire design of your website. This website itself makes extensive use of CSS for every aspect of its design. There is much more to CSS than this brief article goes into, so if you are interested in learning more, please take a look at the “Further reading” links below.

Further reading

Article last updated 3 June 2005
Written by Tom Pike