10 Cascading Style Sheets (CSS)

10.1 What is CSS for?

We have already pointed out that HTML is not a formatting language, and the whole idea is that the author can crack on with getting the important information written down without worrying about how it will be displayed. However we have also seen several cases where it may be desirable to set the exact colour or style of the output. How can we reconcile these conflicting desires? The answer comes in the form of Cascading Style Sheets (CSS).

Styles were added in HTML 4.0, and allow you to define your own particular types of content, and specify everything you like about how each kind of content is displayed. When it comes to writing your web page you simply place a tag to mark what kind of content it is, whether it's a standard HTML tag or one you've specified via CSS. CSS files can inherit properties from other CSS files, hence "cascading".

10.2 Defining Styles

You can specify which style sheets to use in the head section of your HTML document. It's usually convenient to keep these style definitions in separate files so that they can be reused in other pages, and these files are usually given the ".css" extension.

You tell the browser to use a particular stylesheet by adding a <link> tag in the head section of your HTML document:
<link rel="stylesheet" type="text/css" href="my.css">
We won't worry today about exactly what all of these attributes mean, suffice it to say that this is how you apply the styles contained in the file "my.css".

It's important to remember that CSS files are not written in HTML, they have their own syntax. A CSS statement is comprised of three parts: selector, a property and a value. The basic syntax is:
selector {property:value}

The brackets used are "curly brackets", not the normal round ones. The selector is the HTML element you want the style to apply to, the property is the attribute you want to define, and the value is what you want to set that attribute to. E.g., body {color: navy} will set the text in the body of the document to black. Note the curly brackets rather than the usual HTML angular ones. In fact there should never be any HTML marks in a CSS file - CSS is purely to control formatting and other style issues, so that the HTML never has to be concerned with it; and the different syntax is there to emphasise their different natures. If the value is a multiple-word string then you will need to enclose it in speech marks.

You can set more than one property at once, simply separate them by semicolons. E.g.,
p {color: white; text-align="justify"; font-family:"sans serif"}

Likewise you can apply changes to several selectors. This time the selectors are separated by commas:
h1,h2,h3,h4,h5,h6 {color: #00FFFF; text-align="center"; font-family:arial}

Notice that although the selector refers to HTML elements, the property does not always have a direct HTML analogue. Probably the most useful properties at the moment are:

Previous page Next page