back

CSS documentation

CSS for Print & Paged Media

Unlike websites, which are not constrained by any physical document size, paged media are limited by the size of the target page like an A4 page. Fortunately, CSS supports paged media. Let's go through some of the basic concepts and CSS properties that will help you control your document flow on a paged document.

The page size

In CSS you can define a page and a reference to it by name or special selectors (e.g. :left, :right). Use the @page rule to set the relevant page properties.

@page { size: A4; }

This is the minimum requirement for defining a page. Other size options could look like:

@page { size: A4 landscape; size: 400mm 200mm; size: 10in 20in; }

The page margins

Margins can also be defined within the @page - rule.

@page { size: A4; margin: 20mm; }

Printing current and total page number

Assume you want to print the current and total page number on each page at the bottom right corner. Within the @page rule, you also have access to 16 pre-defined margin areas, all of which will automatically position and align. You can read more about those margin areas here.

@page { size: A4; margin: 20mm; @bottom-right { content: 'Page' counter(page) ' of ' counter(pages); } }

The two counters page and pages are special predefined counters that will always return the current page or total document page number respectively.

Adding header and footer

In addition to the 16 pre-defined margin areas mentioned above, you can also define as many area as you want anywhere on the page yourself. Use the @area rule inside the @page rule for that.

@page { size: A4; margin: 50mm 20mm 20mm; @area my-awesome-header { content: 'Here is a page header'; background: red; top: 5mm; left: 20mm; right: 20mm; } }

This works smoothly, but let’s say you want to use an element (e.g. <div id="header">Hello Page</div>) within your document, and position it inside your “awesome-header” area.

@page { size: A4; margin: 50mm 20mm 20mm; @area my-awsome-header { content: element(my-header); background: red; top: 5mm; left: 20mm; right: 20mm; } } #header { position: running-element(my-header); }

You basically define an element at the beginning, that you would like to see as your header, as a running-element, and place it inside your page area. The element then appears printed on every page.

You can read more about paged generated content at www.w3.org, where also more options that facilitate content fine-tuning.