Dziamid
Dziamid

Reputation: 11571

Use CSS to hide contents on print

I’m looking for an easy way to hide everything except a certain div and its contents.

<html>
  <head></head>
  <body>
    <div class="header">...</div>
    <div class="menu">...</div>
    <div class="content">...</div>
    <div class="footer">...</div>
  </body>.
</html>

So, for example, if I want to print only div.content, I would do it like this:

.header, .menu, .footer {
  display: none;
}

And if the layout is complicated, it becomes messy. Is there an easier way to do this with CSS?

Upvotes: 14

Views: 55282

Answers (5)

Dziamid
Dziamid

Reputation: 11571

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.

Upvotes: 8

RoToRa
RoToRa

Reputation: 38390

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;
}

Upvotes: -1

Thiago
Thiago

Reputation: 1555

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.

Upvotes: -1

Tr1stan
Tr1stan

Reputation: 2775

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; }

Upvotes: 7

Sarfraz
Sarfraz

Reputation: 382616

@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" />

Upvotes: 38

Related Questions