As you’ve seen earlier, HTML is made up of tags that define the structure of documents as well as tags that describe the way an element should be displayed in the Web browser. Mixing up structural tags and presentation tags, the way HTML does, can lead to code that is difficult to understand and maintain.
Think of the work involved if you wanted to change the font colour to blue and size to ‘+2’ for all headings in the HTML code shown in Figure 1.4. As you can see, you would have to update the <font> tags on all three headings separately.
HTML rendering result:
Now think of all the work to be done if this update needs to be made over and over again on all the pages on your site! This is not just very tedious work, it’s also very easy to miss one or two spots, leading to an inconsistent appearance of level-three headings on your site.
Now let’s see what happens if we use style sheets instead. If you’ve worked with desktop publishing or word processing software, chances are you’ve used styles to format your document. Styles are formatting rules that you apply to the elements in your documents. Figure 1.5 is the example in Figure 1.4 using style sheets for formatting.
HTML rendering result:
The style sheet is surrounded by the <style> and <style> tags within the head of the HTML document (see Figure 1.6). The h3 element is followed by a list of the formatting rules that will be applied to it, which would display all level three headings as large green text.
Since all the formatting rules are confined to a single location, you can update the style for level three headings in one place only. No more mixing up your structural and your presentation tags in the body of the HTML page.
If you need to use the same style on multiple pages, you can even save the styles in a separate stylesheet file (called ‘styles.css’, for example) and have multiple webpages link to the same stylesheet, as Figure 1.7 shows.
Style sheets bring an explicit separation between the structure of a document and its presentation. To modify the presentation, the change can be restricted to the style sheet alone. Style sheets also offer greater control over fonts, colours, indents, margins, and the general look and layout of your webpages.
The following activity is meant to whet your appetite in using CSS without going into too much detail.
Aside from the appearance of elements, you probably noticed changing the style sheet used can also affect the positioning of the elements on a page.