Limit print area to a div

css, html, printing

Solution

You will have to put all other content into html elements (note the p tag)

<body>
  <p>This should NOT be shown in Print Preview</p>
  <div id="main">
   <p>This should NOT be shown in Print Preview</p>
   <div id="printarea">ONLY this should be shown in Print Preview</div>
  </div>
</body>

Then you can hide all other elements below a parent. do this for each parent in the hierarchy

@media print {
   body *, #main * { display:none; }
   #main, #main #printarea, #main #printarea * { display:block; }
}

EDIT:

this is very similar to the second answer to printing only one div

Problem

Is there a way to print only the nested "id=printarea" div (with styling) using only css (not javascript), in IE8 on Windows? ``` <div id="main"> This should NOT be shown in Print Preview <div id="printarea">ONLY this should be shown in Print Preview <table><tr><th>one</th><th>one</th></tr><tr><td>one</td><td>one</td></tr></table></div> </div> ``` I've tried using css, but it displays nothing (obviously) due to inheritance. The following example shows my intention. ``` @media print { * { display:none; } #printarea { display:block; } } ``` I've successfully used javascript (which works), but I don't consider it an elegant solution, as I'd have to pull in all css imports and style blocks in the document.write. ``` function printDiv(divId){ var divToPrint = document.getElementById(divId); newWin= window.open(); newWin.document.write('<style>table,tr,td,th{border-collapse:collapse;border:1px solid black;}</style>'); newWin.document.write(divToPrint.innerHTML); newWin.document.close(); newWin.focus(); newWin.print(); newWin.close(); } ``` Example: http://jsfiddle.net/D7ZWh/2/ Related: Overriding parent's CSS display property

Original source

Related problems