Creating a Print-Friendly Page with CSS & JavaScript: The McVicar Method

On this page…

    Download & unzip SwitchStyles.zip. You should find 5 files in the directory:

    Download the sample webpage, unzip it, and open media-specific-easy.htm in your text editor. You want to add a print-friendly link on the page in a place you find appropriate. Let's walk through the steps to do so.

    Add the print-friendly link

    First, you need to add a print-friendly link on your web page in an appropriate place. You can do it in two ways.

    Text

    Add the following somewhere on your page:

    <a href="#" onclick="print_preview(); return false;">Print this page</a>
    

    Image

    Add the following somewhere on your page:

    <a href="#" onclick="print_preview(); return false;"><img src="http://www.granneman.com/files/8313/3079/2922/printFriendly.gif" height="23" width="22" alt="Print-friendly"></a>
    

    Fix your screen CSS

    Now let's fix your CSS. The web page already has a link to a CSS file somewhere in the <head>. Find it, and change it so that it only applies to the media of screen. In other words, the initial CSS link will look something like this (don't expect it to look exactly like the example; I want you to have to hunt for it on the webpage):

    <link rel="stylesheet" href="yourcss.css" />
    

    You need to change it so that it now looks something like this (in other words, simply add media="screen":

    <link rel="stylesheet" href="yourcss.css" media="screen" />
    

    Add the print-friendly CSS

    Now you need to add a link in your web page to your print-friendly CSS:

    <link rel="stylesheet" href="yourprintcss.css" media="print" />
    

    Create your print-friendly CSS page, changing & removing things as you like. Test your changes by going to File > Print Preview.

    Add the print-friendly preview CSS

    When you're happy with your print-friendly CSS, & you've made sure that the page will print the way you want it, add the following link to your web page:

    <link rel="alternate stylesheet" href="yourprintcss-preview.css" media="screen" title="Print Preview" />
    

    Create a new CSS file named yourprintcss-preview.css. This is yet another CSS page that the JavaScript will use to give users a preview of the print-friendly CSS. It should contain the following code:

    @import "yourprintcss.css";
    
    #preview-message {
      display: block;
      border: 1px solid #666;
      background: #FF6;
      padding: 2px 5px;
    }
    

    Add the JavaScript

    Add the following link to your web page, in the <head>:

    <script src="print.js"></script>
    

    Finished

    You should now be able to click your print-friendly link and see your print-friendly preview in the browser.

    WebSanity Top Secret