Monday, January 26, 2009

Printing selected portions of a page with CSS

Here's a quick trick to print selected sections of a page using some simple CSS and JavaScript. This post came about after my long fascination with how maps.google.com works to produce a page that has some control buttons on it, but when the "Print" button is clicked (that just contains a simple "window.print" statement), it is able to print out only sections of the page relevant to the data we have tried to obtain. Both maps.google.com and maps.yahoo.com offer the option to print the directions and provide a preview of what the page would look like before one prints it.

Say, for example, I had the following page from which I wanted to print only sections of it out with my printer.


After reading a bit on the media attribute for CSS, I just put together a simple example to illustrate how it works. The code below displays some text and tables, some of which we want to print while the other sections we want to omit. Add the following CSS code to the head section of your page:

< style >
@media print {
.printMeNot {display:none; }
}
< /style >


Now, any sections of the page you do not want present in the printed page, wrap them in a span or a div with the class "printMeNot". That's it!!! No silly iframe methods or need to open another window with just content you want to print. This is how the print preview window would look like:


The file used in the above example can be downloaded HERE.
Browsers tested in: FF 3.0.5, IE8 Beta2, Opera 9.63, Safari 3.2.1 (for Windows) and Google Chrome 1.0.154.43.

Happy printing!!!