Creating printer-friendly websites

I recently added some print-specific rules to my CSS. People often forget that websites can be printed, so I thought I would put in the effort to research some best practices and apply these to my website.

What follows are both general and specific guidelines that you can use with your own print styles.

General print style guidelines

Reset coloured backgrounds to white

The less there is to print, the better. Most browsers have a "Hide backgrounds" option but it doesn't hurt to just do this by default.

If a background is being used to separate content, use a thin border with padding as a printer-friendly alternative.

Set all text to black

Setting all type in black is easier to print and creates a better contrast on paper. One could consider this an economical benefit for the user.

Use page breaks to avoid content being split

There are no rules as to how a website should display across multiple pages when there is a large amount of content. In the case of this website, components like code blocks or quotes can be split across two pages, which is less than ideal.

For content that should remain as one block, the page-break-inside selector will force lengthy elements to be moved to a new page rather than split across two.

pre {
  page-break-inside: avoid;
}

It should be remembered that printing on the web will never be as sophisticated as printing from a dedicated word processor, so there will always be some hiccups when using the various page-break selectors.

Extra things to consider

Setting custom page margins

If you want to set a custom page margin, you can do so with the @page selector. Use the mm unit when setting the margin, since this rule targets printed material.

At the time of writing, I currently use the following, though it is rather generous:

@page {
  margin: 20mm;
}

As the very nature of the web is hyperlinks, it might be useful to display the URLs beside any hyperlinked text. This can be done with the following:

a[href^="http"]:after {
  content: " (" attr(href) ")";
}

…which will format the following HTML…

<p>This is a <a href="http://example.com">hyperlink</a>.</p>

…into this:

This is a hyperlink (http://example.com).