Selecting regions of a webpage to print

One of the most common needs when formatting a webpage to print is turning off regions that don't need to be displayed. As explained in the full tutorial, this is usually done with display: none; as follows:

@media print
{ 
 .no-print, .no-print *
 {
 display: none !important;
 }
}

With the above CSS, you could add class="no-print" to any HTML elements you don't want printed. More commonly, the CSS might specify by class or id all of the elements not to print.

This approach starts to break down if all of the content to be printed in already in a specific element, and everything else on the page (of which there might be a great many), should not be printed. In this case, what we really want is a way to say "print nothing but this particular element." That can be achieved with the visibility command. Here's an example of the CSS:

@media print {
 body * {
 visibility: hidden;
 }
 #section-to-print, #section-to-print * {
 visibility: visible;
 }
 #section-to-print {
 position: absolute;
 left: 0;
 top: 0;
 }
}

This approach works because while display:none; forces all descendants to not display, with visibility: hidden;, it's still possible to turn on visibility for descendants.

I found this approach on stackoverflow. Some of the comments suggest it works best when the content to be printed is only a single page. For multiple output pages, one possible approach is to set both the target and all its parents to overflow:visible; position:absolute !important; top:0;left:0.

Sources:

 

More from Will

Code Tutorials

Here are Will's detailed code tutorials that we have migrated to Print Fundamentals for Developers on the HP Developers' Portal

Will's blog and forum posts