Print Styles with CSS

Same Code with a Print StylesheetA CSS cliche is that it allows you to separate content from presentation, but what the *%$*# does that mean?

Well try this for size – how about having two stylesheets controlling the same page one for screen, the second for print...

For instance if you were to print this page you wouldn't want to see the Atomz search, the site logo (which looks horrible out of a white background), or the navigation. So wouldn't be good to tell them not to print...

Same HTML, different stylesheets. To your left we have a screen grab of how this very page (or one very like it) might print. How do you achieve this wonder? Read on...

Linking to alternate stylesheets

Pointing a browser towards a print stylesheet is as easy as adding another <link> tag to the <head> of your document. You need two tags, one for each stylesheet.

Here's what they might look like:

<link rel="stylesheet" type="text/css" media="print" href="printStyles.css">
<link rel="stylesheet" type="text/css" media="screen" href="screenStyles.css">

This example assumes you've two stylesheets parked on your site called printStyles.css and screenStyles.css, each one suitable for their task.

The really important bit of both the above tags is the media="?" portion. This media attribute tells a browser which stylesheet to use for whatever device is going to have to deal with the page. I've not put many of these to the test (apart from print, and screen) but others include: braille, handheld ,projection , and tv. Incidentally, if you use Dreamweaver, even sadly Dreamweaver MX, then including two styles can make it render your pages awful funny, so watch out. My experience is that things are great in the browser and lousy in Dreamweaver.

(Dreamweaver MX 2004 renders correctly however.)

Setting up and testing a print stylesheet

One you've linked to an alternate stylesheet you can see what it'll look like when it's printed by using the Print Preview option in your browser.

I found it easiest to make a copy of my initial screen stylesheet and to then go through it ammending each style so's it was fit to print. When you're doing this you'll find that you want to surpress the print out on quite a lot of page elements, like ad banners, navigation, dark backgrounds.

The secret to doing this is the CSS property display. The default setting for most elements is to display, so it's not a property that gets set very often. However if you want to get rid of a page element then setting it's display to none works very well.

Syntax looks something like this

#banner {display:none;}

Take a look at my print stylesheet for this page to get the general idea.