Synook

CSS for print media

Some people like to print out websites, but with modern layouts and graphics the result isn’t always pleasant. However, using CSS to define sepearate and additional rules for print media is not difficult.

One of the primary tools the CSS specification gives us is a mechanism to specify different sets of rules for different media types, such as print, or projection (full list here). However, for this article we will just look at the print media type.

There are two ways to explicitly state the media type for a stylsheet. The first is to create another element with the media attribute set to print.

If you like to reduce clutter, however, you can also use the @media CSS directive to define the set of rules within your CSS code.

@media print { /* Print only rules here */ }

The primary aim of this new print-only stylesheet is to hide layout elements and other artifacts, such as forms, that are useless on paper, which can be achieved through the use of the display and visibility properties.

Besides print-only stylesheets, there are also a few attributes defined in CSS specifically with printing in mind.

Particularly of note are the three page-break properties, page-break-before, page-break-after, and page-break-inside. These allow you to specify where page breaks should (or should not, in the case of page-break-inside) occur. The possible values for these attributes are always, auto, avoid, left, right and inherit for -before and -after, and auto, avoid, and inherit for -inside. Setting always forces a page break in the specified position, while avoid prevents one. The left and right values are similar to always. For example, if you wanted to have a new page before every h1 element, but none inside paragraphs, you could write your CSS thus:

h1 { page-break-before:always; } p { page-break-inside:avoid; }

A full explaination of the paging ability of CSS can be found on the W3C’s site at http://www.w3.org/TR/CSS2/page.html

There are many other ways that you can alter your stylesheet to make your website more print-friendly, such as by using a serif font or increasing margins, or explicitly setting the orientation. Experiment!