Print Styles with CSS
One of the great CSS cliches is that it allows you to separate content from presentation, but what the *%$*# does that mean when it’s at home?
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 probably wouldn’t want to see the search, the site logo or the navigation. So wouldn’t be good to tell them not to print…
Same HTML, different stylesheets.On the left we have a screen grab of how this very page looked when this article was written and on the right, how it would print 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" media="print" href="print.css">
<link rel="stylesheet" media="screen" href="styles.css">
HTML 5, unlike older versions of HTML, doesn’t require you to define a type attribute to your link elements. Instead it assumes that you’re using CSS – and seeing as CSS is the only way to style HTML it’s about time too.
This example assumes you’ve two stylesheets parked on your site called styles.css and print.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.
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 amending each style so’s it was fit to print. When you’re doing this you’ll find that you want to suppress 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;}

