CSS Reference ยท At-rules
The @page at-rule
Reference for the CSS @page at-rule: set paper size, margins and orientation for printing, use :first, :left and :right pages, with examples.
The @page at-rule styles the page box used when a document is printed or exported to PDF. It controls things the normal box model cannot: the paper size, the page margins and (in some browsers) the headers and footers placed in the margin boxes.
It only affects printing. On screen it does nothing, so you check it with print preview or by saving to PDF.
@page { size: A4; margin: 2cm; }
Try it
The preview below cannot print, so this page paints a mock sheet with the same margins that @page would use, and shows the rules in the code. Open print preview on a page of your own to see the real effect.
Syntax
@page [<page-selector>]? { size: A4 | letter | landscape | 210mm 297mm; margin: <length>{1,4}; /* margin boxes (limited support) */ @top-center { content: "Report"; } @bottom-right { content: counter(page); } } /* page selectors */ @page :first { } @page :left { } @page :right { } @page :blank { } @page wide { } /* named page; use with page: wide; */
- Allowed properties are limited:
size,margin,margin-*,page-orientation, plus a few box and background properties;padding,border,widthandheightof the page box are not meant to be used. sizeaccepts keywords (A4,A3,letter,legal),portrait/landscape, or one or two lengths.
Values
| Syntax and arguments | Description |
|---|---|
size: A4 landscape |
Paper size and orientation. |
size: 8.5in 11in |
Explicit width and height. |
margin: 2cm |
Page margin on all sides. |
@page :first |
The first printed page. |
@page :left / :right |
Left- and right-hand pages of a double-sided print. |
@page :blank |
Pages added as intentionally blank. |
@page name |
A named page type, assigned to elements with the page property. |
@top-center { ... } |
A margin box for headers or footers. |
Usage notes
- Page margins are not box margins.
@page marginis the paper margin;body { margin }is added inside it. - Test in print preview or "Save as PDF"; screen layout tells you nothing.
- Pair with
@media printto hide navigation and use readable colours when printing. - Control breaks with
break-before,break-afterandbreak-insideon elements; usebreak-inside: avoidfor figures and table rows. - Margin boxes and page counters (
content: counter(page)) work in Chromium-based browsers but not in all engines. Dedicated PDF tools (print-to-PDF libraries) support them more fully. - User settings win. Users can override the paper size and margins in the print dialog.
- Mixed sizes use named pages:
page: wide;on a table or section moves it to its own page type.
Browser support
The basic @page with size and margin works in current browsers. Support for :blank, named pages and margin boxes is uneven; check the engines you need.
Related
@media@counter-style- Lesson: Print Styles
- Lesson: Counters