How to Print
a specific Part of a HTML Page using CSS (@media:screen,@media:print)
The user can click on a link or button in the HTML page or form, e.g.
add the following HTML code:
<a href="javascript:window.print()">Print</a>
The problem is, that the print command will print the whole page, which
might not be useable.
The solution is to define 2 different CSS styles
for the screen and the printer, so that unwanted parts of the page will
be hidden when printing.
How it works:
The following sample should illustrate how easy it works!
The page
contains 3 parts: header, middle and footer and only the middle part should
be printed.
First we need to define the parts ... this can be done using e.g. <div> tags.
...
<div class="noprint">
page header
</div>
...
this part of the page contains
the part we want to print, e.g. the form
...
<div class="noprint">
page footer
</div>
...
Now let's define the CSS code
The specific CSS code can be defined directly in the HTML header or using a stylesheet file.
<html>
<head>
...
<style
type="text/css">
<!--
@media print
{
.noprint {display:none;}
}
@media screen
{
...
}
-->
</style>
...
</head>
...
The code above contains the code if you want to add the CSS code directly to the HTML header. The class definition noprint sets display:none, so the content will be hidden when printing the page. Its also possible to use a <span>, <p> or <table> tag instead of <div>. Using ID will work the same way.
That's all. An alternative would be to use 2 different CSS files (see below)
The following code shows how to use 2 different CSS files: one for the screen and one for the printer
The usage is quite simple, make a copy of your CSS file and remove all the unwanted parts using display:none; in the "style-print.css".
...
<head>
...
<link rel="stylesheet"
href="style-screen.css" type="text/css" media="screen">
<link
rel="stylesheet" href="style-print.css" type="text/css"
media="print">
...
</head>
...