iamcal.com

[home] [PDF Version]

Blog Hacks : Skinning with stylesheets

Originally published 20th June 2003

It's possible to provide users with a choice of stylesheet for viewing your weblog. This can be fun, but also serve a more useful purpose. By providing alternative stylesheets, you can offer a large text, high contrast version of your site, without having to make two versions of your pages.

This is made possible by specifying alternative stylesheets:

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

Browsers are supposed to allow users to switch between these stylesheets, but only mozilla does at the moment. With some javascript trickery, it's possible to get around this. Grab the javascript file (available from http://code.iamcal.com/js/scheme_switcher/) and put the following in your <head> section:

	<script src="styles.js" language="Javascript" type="text/javascript"></script>

Once you've done this, you'll need to create some stylesheets. For each stylesheet, add a <link> tag to your <head> section:

	<link rel="alternate stylesheet" type="text/css" title="default" href="green.css" />
	<link rel="alternate stylesheet" type="text/css" title="hello"   href="hello.css" />
	<link rel="alternate stylesheet" type="text/css" title="world"   href="world.css" />

It's important to give one of your stylesheets a title of "default". This stylesheet will then be loaded first.

For each stylesheet you add, you'll need some way for users to be able to switch to it. To do this, you simply need to call the function setStyleSheet(), defined in the javascript file earlier.

	<a href="#" onclick="setStyleSheet('default'); return false;"
		onkeypress="this.onclick();">default</a>
<a href="#" onclick="setStyleSheet('hello'); return false;" onkeypress="this.onclick();">hello</a>
<a href="#" onclick="setStyleSheet('world'); return false;" onkeypress="this.onclick();">world</a>

The script uses cookies, so if the user has cookies enabled then the stylesheet used will be remembered and automatically selected on subsequent visits.