Question

When printing a page from a browser, it refers to a print.css stylesheet declared with media="print". The browser disables some CSS rules like background-image and background-color, some browsers have options to enable them.

As told in this answer, it is not possible to override this behaviour from the page code.

I have two questions about this:

  • Is there any documentation or good reference about these printing rules ? For example:
    • Which CSS rules are disabled ?
    • Can Javascript do something on the page before printing ?
  • Is there a way to detect a browser in printing mode with Javascript and then make a graceful degradation system ?
Was it helpful?

Solution

How browsers print pages is a bit of a black box; I haven't been able to find any definitive references.

All major browsers have print options to "shrink to fit" the web page to the paper page (enabled by default), and to print background images and colours (disabled by default). Most users will leave these defaults as-is, if they are even aware these options exist. I haven't seen browsers "disabling" any other CSS rules when printing.

Firefox and IE support the onbeforeprint and onafterprint events, so you can detect when printing is happening with JavaScript, though obviously this isn't a cross-browser solution.

Most adjustments needed for printing can be handled by CSS (either in a separate print stylesheet or as a @media print { ... } block in your main stylesheet):

  • The CSS-Discuss Wiki has a good page on how much you can control through CSS.

  • I suggest having a look at the print styles from HTML5 Boilerplate as a good starting point.

  • If you have background images that must be printed, you can include <img> elements in your page, hidden with display: none, then make them visible with display: block (or inline) in your print CSS.

If you need to heavily modify the page for printing, I suggest offering a separate print-only version of the page, rather than trying to make adjustments with JavaScript.

OTHER TIPS

Not sure about the first point, but to detect browser in printing mode, you can do the same as for screen. Either use Modernizr and conditionally add classes to for supported features, then make targeted CSS rules like:

body.whateverfeature .yourrule { }

or if it's just IE you want to test for, use something like h5bp does:

<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top