Printer-Friendly Page With CSS

Monday, July 7, 2008

Ok, so you want to create a printer-friendly page without having to create another web page for that purpose. Here's how.

First, create a separate stylesheet with the rules for the page to be printed. Usually, this css is named print.css, so maybe you should name your it print.css too :D.

Second, link the stylesheet to the page and set the media property to print.
<link rel="stylesheet" type="text/css" href="base.css" media="screen" /> <link rel="stylesheet" type="text/css" href="print.css" media="print" />

You see, the default value for the media attribute is all, so if you don't specify the attribute the browser will apply the CSS rules to all media. There are actually ten media types:

Media Type Description
all Suitable for all devices
braille For Braille tactile feedback devices
embossed For paged Braille printers
handheld For handheld devices
print For paged material, documents viewed on-screen in print preview mode
projection For projected presentation, i.e projectors
screen Primarily for color computers screens
speech For speech synthesizers
tty For media using fixed-pitch character grid i.e teletypes, terminals, or devices with limited display capabilities
tv For television-type devices


If you want to define the stylesheet for several media, separate the media values with comma, like this
<link rel="stylesheet" type="text/css" href="dual.css" media="print, projection" />

And beside using link method, you can also use import, like the following line @import URI(dual.css) print,projection; And stil there's way to define stylesheet and media types, it's by using the @media, which enables writing css rules that can be set for different media, all in one stylesheet
<style type="text/css">
@media print{
 #container {
  font-size: 10pt;
  background: #FFFFFF;
  color: #000000 
 }
}

@media screen{
 #container {
  font-size: .8em;
  background: #0000FF;
  color: #FFFFFF 
 } 
}
</style>


Hope this helps.

0 comments: