Print <div id="printarea"></div> only? Print <div id="printarea"></div> only? javascript javascript

Print <div id="printarea"></div> only?


Here is a general solution, using CSS only, which I have verified to work.

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

Alternative approaches aren't so good. Using display is tricky because if any element has display:none then none of its descendants will display either. To use it, you have to change the structure of your page.

Using visibility works better since you can turn on visibility for descendants. The invisible elements still affect the layout though, so I move section-to-print to the top left so it prints properly.


I have a better solution with minimal code.

Place your printable part inside a div with an id like this:

<div id="printableArea">      <h1>Print me</h1></div><input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Then add an event like an onclick (as shown above), and pass the id of the div like I did above.

Now let's create a really simple javascript:

function printDiv(divName) {     var printContents = document.getElementById(divName).innerHTML;     var originalContents = document.body.innerHTML;     document.body.innerHTML = printContents;     window.print();     document.body.innerHTML = originalContents;}

Notice how simple this is? No popups, no new windows, no crazy styling, no JS libraries like jquery. The problem with really complicated solutions (the answer isn't complicated and not what I'm referring to) is the fact that it will NEVER translate across all browsers, ever! If you want to make the styles different, do as shown in the checked answer by adding the media attribute to a stylesheet link (media="print").

No fluff, lightweight, it just works.


All the answers so far are pretty flawed - they either involve adding class="noprint" to everything or will mess up display within #printable.

I think the best solution would be to create a wrapper around the non-printable stuff:

<head>    <style type="text/css">    #printable { display: none; }    @media print    {        #non-printable { display: none; }        #printable { display: block; }    }    </style></head><body>    <div id="non-printable">        Your normal page contents    </div>    <div id="printable">        Printer version    </div></body>

Of course this is not perfect as it involves moving things around in your HTML a bit...