1.3 Linking CSS

Undoubtedly the best method to implement CSS so far is to use a seperate file altogether, called a stylesheet, in which to define all the properties for elements. This is a simple text file often saved as "style.css". Referring back to our basic website example in the section on HTML, add the following self-closing tag complete with its attributes into the head section:

<link rel="stylesheet" type="text/css" href="style.css" />.

So we now have:

<html>
 <head>
  <title>My very first website</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
 </head>
 <body>
  <p>Hello World!!!</p>
 </body>
</html>

The <link> tag tells the browser where to find the stylesheet (note the whole stylesheet could be added in the head section instead of this link but this would lead to heavier web pages).

Next create a new file in notepad, and copy and paste in the following code:

body	{background-color: #ff0000;}

Using the <body> tag as the selector, this tells the browser to set the background colour of the body of the web page to red (again note the colours are specified in hexadecimal - see the section on attributes).

Choose "Save as..." under "File" in the top menu, then "All Files" in the "Save as type" box, and save your document as "style.css in the same location as your.html files. The .css extension indicates it is a CSS document. The basic file layout for a website is shown below:

File Layout

Now open your index.html web page in your browser, and it will have a red background. This may seem a small step but a whole host of properties (attributes) can be specified in the style sheet that will affect the layout of the web page without adding bulky code to that webpage. Below are a few examples:

h1	{color: red;
	font: 18px verdana, arial, helvetica, sans-serif;}

p	{color: blue;
	font: 12px verdana, arial, helvetica, sans-serif;}

Defining the layout of html documents from a seperate file, rather than by adding styling (in other words, attributes) to tags in every web page (as used to be the norm) has obvious benefits. If a website has many pages, only one file needs creating to style all these pages, resulting in less code per page. This has additional benefits such as faster page loading and less data transfer (remember that most web hosting packages have monthly data transfer limits). Also, if a web designer wishes to redesign the layout of a website, only one file needs altering rather than multiple pages.