I’m looking for an easy way to hide everything except a certain div and its contents.
Assign a separate CSS file that defines the behaviour when printing a web page.
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
and then within that file just define:
.header, .menu, .footer { display: none; }
I did it css3 way: using not pseudo class and direct ancestors (children)
/* hide all children of body that are not #container */
body > *:not(#container) {
display: none;
}
/* hide all children of #container that are not #content */
#container > *:not(#content) {
display: none;
}
/* and so on, until you reach a div that you want to print */
#content > *:not(#print_me) {
display: none;
}
This way you can eliminate everything except what you want to print even in very complex layouts. :not is very efficient here because it takes care about any future modifications of you html.
Depending on your HTML structure (and browsers you need to support, because IE6 won't support this), you could hide all top-level divs and just show the one/few you want to show:
body > div {
display: none;
}
#content {
display: block;
}
@media print {
.noPrint {
display:none;
}
}
Now you need to apply the class noPrint
to the elements you want to hide in printing.
It is good practice to use a style sheet specifically for printing, and and set it's media attribute to print
.
Example:
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
You can use classes.
.classHide{display: none}
Depending on the language you are using, when if==true you can add a class to header, menu and footer.
So you won't need to use another css file.