Styles (continued)

In the last tutorial we looked at how to identify the parts of our web page that we want to put in specific positions or display in certain fonts and colours by adding id and class attributes to the various tags. To actually apply styles based on those attributes we need to attach stylesheet commandx to our page.

There are three ways to attach stylesheet commands into your web page.

The best way is to use separate files for your stylesheets and link them to your page. To attach the stylesheet(s) into your page and identify which of them is to be used when using link tags we simply add the tags immediately before the </head> tag like this:

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

The type attribute always has this value when linking a stylesheet as this is what identifies that it is a stylesheet. The rel attribute can be either "stylesheet" for a stylesheet to be used by the page or "alternate stylesheet" for one that you want to have available but not actually use. The href attribute defines which file contains the stylesheet definition. All three of these attributes must be present for the stylesheet link to work.

There are also a couple of optional attributes. media defines where the stylesheet is to be used with the most common values being "all", "screen", and "print" (although there are lots of others). We can also assign a title oif we wish to be able to easily distinguish between multiple stylesheets.

The second way to add stylesheet commands to your page is to enclose them within style tags (which also go immediately before the <head> tag.

/* stylesheet commands go here */

When we do it this way then any media restrictions on when the styles are to be applied will need to be coded in the stylesheet itself.

Note also that the entire stylesheet content needs to be enclosed within a special <![CDATA[ ]]> tag in order to ensure that the content of the stylesheet is not interpreted as XHTML. This special tag is similar to the DOCTYPE tag in that it doesn't need to be closed.

The third method of attaching styles to your page is to do use the style attribute to add them directly to the tags to which specific styles are to be applied.

As your site will be easier to maintain if the XHTML and stylesheets are kept separate I recommend that you use only the first of these three methods for your finished pages and only use the second and third methods while you are testing the effect that applying certain styles will have on your page during development of your page.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow