The page box / @page
How to use the @page rule for PDF output
@page declares the properties of the page box itself: its dimensions and its margins, which are things no element selector can reach.
What it is for
Everything else in CSS styles boxes inside a canvas. @page styles the canvas. It is the only place you can say how big the paper is, and it exists because a scrolling page has no such concept to inherit from.
Support: Works in a browser-based render
The rule itself and the size and margin descriptors work. The margin boxes inside it, meaning @top-center and its fifteen siblings, do not: those are the part that dedicated print engines implement and browser engines do not.
The syntax
Written the way it would appear in a document stylesheet, using @page as intended.
@page {
size: A4 portrait;
margin: 18mm 16mm;
}
/* A different margin on the first page, for a letterhead. */
@page :first {
margin-top: 42mm;
}The mistake people make
Setting the size here and also passing a page format in the render options. The two disagree and which one wins depends on the engine, so the document comes out the size you did not choose, on some renders and not others.
Frequently asked
Does @page work when generating a PDF?
Works in a browser-based render. The rule itself and the size and margin descriptors work. The margin boxes inside it, meaning @top-center and its fifteen siblings, do not: those are the part that dedicated print engines implement and browser engines do not.
How would I know if it were not working?
You would not, from the CSS. Unimplemented and unmatched CSS both fail silently, which is why the reliable test is to set a deliberately extreme value and see whether anything changes. If a 40mm margin looks the same as an 18mm one, the rule is not reaching the page.
Related properties
Things that come up in the same part of a document stylesheet.
How to set the PDF page size in CSS
size. Works in a browser-based render.
How to set PDF page margins in CSS
margin (in @page). Works in a browser-based render.
How to style the first page differently in a PDF
@page :first, :left, :right. Works in a browser-based render.
How to make one section landscape in a portrait PDF
page (named pages). Only in dedicated print engines.
How to put a running header in a PDF with CSS
@top-center and the margin boxes. Does nothing in a browser-based render.
Every property, with its support status
The full reference, grouped by what part of the page it touches.
Paste the CSS and see what the rendered page does with it.