Thursday, July 28, 2005

CSS Tip: Using media=print for printer-friendly pages

[This was originally posted at]

When you print a page, you want just the workspace of the page in normal portrait view - not banner ads, left navigation bars or text that extends off the printed page . This is a printer-friendly view. There are at least two categories of solutions:

  1. Have a "click here for printer-friendly version" link that posts back to the server, does manipulation such as hiding menus, and creates a new instance of the page in printer-friendly mode
  2. Use Cascading Style Sheets (CSS).

The former has several problems that the latter solves:

  • It posts back to the server, which hurts performance
  • It becomes a nightmare if you want to open a new instance of the page for printing, such that closing this print-page won't accidentally close the main app page.
  • It is a pain for editable pages because it requires the developer to manually persist all values to the new print page. Say the user enters a value in a text field, how do you persist that to a new page instance, perhaps via querystring or session? But what if the values are large?
  • It requires additional effort for each page.

CSS provides a "media" attribute that can apply different style sheets to different media. The two media we're looking at here are screen (default) and print.

A stylesheet can set the color, visibility, or any other style that's relevant to a print-version. Here's a practical example that hides buttons (you can click a button in printview) and formats all text in greycolor (you many not want to waste color printing on text):

Html page:

        <LINK href="Print.css" type="text/css" rel="stylesheet" media="print">
        <LINK href="StyleSheet1.css" type="text/css" rel="stylesheet" media="screen">
    <body MS_POSITIONING="FlowLayout">
        <form id="Form1" method="post" runat="server">
            <P>This tests styles.P>
                <asp:Label id="Label1" runat="server" CssClass="MainFont">
                <asp:Button id="Button1" runat="server" CssClass="PrintButton"

Stylesheet (Normal):

    font-weight: bold;
    color: red;

Stylesheet (Print):

    display: none;
    display: none;

Eric Myer has a great article that explains how to use CSS for printing.

No comments:

Post a Comment