I'm stumped.
I have a box model that is controlled by css in other parts of a CMS.
For simplicity, lets say it's like this:

<div.a>
    <div.b>
        <table>
        </table>
     </div>
</div>

I wish to print the raw table in the midst of the divs without the CSS margins assigned to them or to print the table alone.

To do this I would use :

@media print{
div.a,div.b {display:none}
}

The problem is that everything inside that box vanishes also.
Is there a way to accomplish the table print with CSS?

Dani AI

Generated

Short summary and a couple of practical alternatives that avoid hiding the table entirely. and were correct that resetting the outer divs for print fixed 's case. If you need a solution that removes the wrapper boxes without touching global layout rules, try one of these.

One CSS-only trick is to make the wrappers behave as if they are not boxes at print time by using display: contents. It lets the table participate in the page flow as though the wrappers were not there. Support and accessibility vary though, so test it before relying on it in production. See display on MDN and current support at Can I Use.

@media print {
  .a, .b { display: contents; }
}

If CSS fallbacks are impractical, generate a print-only document with JavaScript: clone the table into a new window (copy minimal styles), call print, then close the window. This is reliable across older browsers and lets you control exact print styling.

function printTable(selector){
  var table = document.querySelector(selector);
  if(!table) return;
  var w = window.open('', '_blank');
  w.document.write('<!doctype html><html><head><title>Print</title>');
  Array.prototype.slice.call(document.querySelectorAll('link[rel=stylesheet], style'))
    .forEach(function(n){ w.document.write(n.outerHTML); });
  w.document.write('</head><body>' + table.outerHTML + '</body></html>');
  w.document.close();
  w.print();
  w.close();
}

Notes: copy any critical print CSS into the print document; display: contents can affect screen readers; test print preview across browsers.

Recommended Answers

All 3 Replies

You probably want to set them to width: 100%, margin: 0, padding: 0.

margin:0;
padding:0;

Thanks guys
That seems to be the solution.
Just set all of the margin, padding and width stuff to 0.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.