There may be times in which your website or application would like to improve the user's experience when printing content. There are a number of possible scenarios:

  • You wish to adjust layout to take advantage of the size and shape of the paper.
  • You wish to use different styles to enhance the appearance of your content on paper.
  • You wish to use higher resolution images for a better result.
  • You want to adjust the user experience of printing, such as presenting a specially-formatted version of your content before printing begins.

There may be other cases in which you want to manage the printing process, but these are some of the most common scenarios. This article provides tips and techniques for helping your web content print better.

Using a print style sheet

Add the following to your <head> tag.


<link href="/path/to/print.css" media="print" rel="stylesheet" />

Using media queries to improve layout

You can use the CSS @media at-rule to set a different appearance for your webpage when it is printed on paper and when it is displayed on the screen. The print option sets the styles that will be used when the content is printed.

Add this at the end of your stylesheet. Note that specificity and precedence rules still apply:


@media print {
  /* All your print styles go here */
  #nav {
    display: none !important;

Detecting print requests

Browsers send beforeprint and afterprint events to let content determine when printing may have occurred. You can use this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process).


Here are some common examples.

Automatically close the window when finished

The following example will close the window after the user has printed its contents:


window.addEventListener("afterprint", () => self.close);

If you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: HTMLIFrameElement), automatically removing it after the user prints its contents. The following is a possible example which will print a file named externalPage.html:



<button id="print_external">Print external page!</button>



function setPrint() {
  const closePrint = () => {
  this.contentWindow.onbeforeunload = closePrint;
  this.contentWindow.onafterprint = closePrint;

document.getElementById("print_external").addEventListener("click", () => {
  const hideFrame = document.createElement("iframe");
  hideFrame.onload = setPrint; = "none"; // hide iframe
  hideFrame.src = "external-page.html";

See also