Limit printable area to div

Is there a way to print only the nested "id = printarea" div (with style) 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 tried using css but it doesn't display anything (obviously) due to inheritance. The following example shows my intention.

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

I have successfully used javascript (which works), but I do not think this is an elegant solution, since I would have to use all the importers and style blocks in the document.write document.

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 the parent CSS display property

+4
source share
3 answers

html ( p)

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

.

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

EDIT:

div

+5

, , . , -

#main * {display:none;}
#main #printarea {display:block;}

, #main , . ​​

+1

, , , , , , (-), . , , CSS DOM, . - :

@media print {
   #main {position:relative; padding:0; height:1px; overflow:visible;}
   #printarea {position:absolute; width:100%; top:0; padding:0; margin:-1px;}
}

This will cause the div to collapse #mainand place it #printareaon top of it so that it covers everything. (I added margin:-1pxthat he also close the border #main). Just be sure to #printareahave a background, and you should be good to go.

Try printing the display frame from this script: http://jsfiddle.net/D7ZWh/3/ to see the result.

+1
source

All Articles