Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CSS to hide contents on print

Tags:

css

printing

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?

like image 419
Dziamid Avatar asked Jan 27 '11 13:01

Dziamid


People also ask

How do I hide the elements when printing a website using CSS?

To hide the element, add “display:none” to the element with CSS.

How do you hide content in CSS?

You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.

Can we apply CSS to page for printing?

You can use CSS to change the appearance of your web page when it's printed on a paper. You can specify one font for the screen version and another for the print version.

What is hidden print?

"Hidden Pattern Print" is a function provided for the purpose of deterring unauthorized printing, but not a function that prevents information from being leaked.


2 Answers

@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" />
like image 171
Sarfraz Avatar answered Oct 11 '22 23:10

Sarfraz


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.

like image 42
Dziamid Avatar answered Oct 11 '22 21:10

Dziamid