Lesson 47 of 52Beyond the screen
Print Stylesheets and Paged Output
Make pages print well and turn HTML into PDFs: @media print, @page, page breaks, background colours, and the tools teams use for invoices.
So far every lesson has targeted a screen. This short unit covers two places your HTML ends up that are not a browser window: paper and the inbox. A customer support ticket lands on your desk: "When I print my invoice, the page is three sheets long, the logo bar takes up half of page one, the total is cut in half across two pages, and the paid badge is invisible." Nobody on the team has looked at the site on paper, because nobody prints any more. Except accountants, travellers, people applying for visas, and anyone your product sends a receipt to. Print is also how most PDFs get made: when a backend "generates an invoice PDF", it usually renders HTML and prints it. This lesson teaches the paged side of CSS, so that the printed or PDF version of a page is designed, not left to chance.
Paper is a different medium
On a screen, a page is one long scrolling column of whatever width the window is. On paper it is a stack of fixed rectangles, usually A4 (210 by 297 mm) or US Letter (8.5 by 11 inches). Content has to be cut into those rectangles. CSS calls this fragmentation: the browser lays the page out at the paper width, then slices the result into page boxes, deciding where each cut falls.
Three other things change when a browser prints:
- Nothing is interactive. Menus, buttons, search boxes, cookie banners and video players are dead weight on paper.
- Links cannot be clicked. "Read our terms" is useless unless the URL is printed too.
- Backgrounds are dropped by default. Chrome, Firefox and Safari all leave out background colours and images unless the user ticks a box ("Background graphics" in Chrome) in the print dialog. This saves ink, and it is why that green paid badge disappeared: it was white text on a green background, and the background went.
Each printed page is a page box with a fixed size. You choose it with @page { size: A4; }, though the user's printer settings can still override it.
Turning print styles on
Print styles are just a media query. Responsive Design used @media (width >= 768px) to react to the screen. Here you react to the output medium:
@media print {
.site-nav, .cookie-banner, .chat-widget, button { display: none; }
body { font-size: 11pt; color: #000; background: #fff; }
}You can also put print rules in their own file and attach it with the media attribute. The browser still downloads it, but at a low priority, so it does not block the first render of the screen page:
<link rel="stylesheet" href="/print.css" media="print">The opposite also exists: @media screen wraps rules that should never reach paper, such as a sticky header. Many teams prefer this direction for big layout rules, so print starts from plain document flow instead of having to undo grid layouts and sticky positioning one by one.
To see print styles without wasting paper, use the browser's print preview, or better, DevTools. In Chrome, open the Command Menu (Cmd+Shift+P on macOS, Ctrl+Shift+P on Windows), type "Rendering", and set Emulate CSS media type to print. The page stays live, so you can inspect elements and edit print rules as you would screen rules. Emulation shows the print styles but not the page cuts, so check breaks in real print preview.
A print stylesheet you can try
The preview below cannot open a print preview by itself, so it has two buttons. Toggle print styles flips the media attribute of the print <style> element between print and all, so the same rules apply on screen. Print calls window.print() and opens the real dialog for this preview. The button bar itself is hidden by a separate @media print rule in the first style block, so it never reaches paper but stays on screen while you toggle.
Preview
Press the toggle. The nav vanishes, the link prints its URL after it, and the layout widens to the page. Press Print and look at the dialog: with "Background graphics" off, the badge still keeps its green because of print-color-adjust: exact. Delete that line, print again, and the badge turns into white text on white paper. That is the original support ticket.
What to hide, what to reveal
A good print stylesheet is mostly decisions about content.
Hide anything that only works on a screen: navigation, search, sidebars of related links, ads, share buttons, chat widgets, cookie banners, video embeds, "back to top" links, and form controls the reader cannot use. A utility class such as .no-print helps for one-off cases, but naming the real components in the print stylesheet scales better than sprinkling a class through the markup.
Reveal what the screen hid behind interaction. Print the target of external links with attr(href) as in the demo. The ^="http" part skips in-page anchors such as #section-2, which mean nothing on paper. Expand collapsed accordions and details elements if the content matters, since nobody can click them open on paper. Show the full text of truncated cells. For abbreviations, abbr[title]::after { content: " (" attr(title) ")"; } prints the expansion.
Reset colour. Dark themes print as a block of solid ink, or worse, as light grey text on white once the browser drops the dark background. Set text to black and the background to white, remove shadows, and swap light grey text for something darker. Paper has no backlight, so contrast that is fine on a screen can be too faint in print. Points (pt) are fine for print font sizes; 10 to 12pt is normal body text.
Backgrounds and print-color-adjust
print-color-adjust has two values. economy, the default, lets the browser make ink-saving changes such as dropping backgrounds. exact asks it to print the element's colours and backgrounds as written. Use it on the few things where colour is information: status chips, chart bars, a coloured legend, a boarding pass header. Write both the prefixed and unprefixed forms, because Chromium-based browsers and Safari relied on -webkit-print-color-adjust for years:
.status-chip, .chart {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}Use it sparingly. Forcing a full-page dark background costs the reader a lot of toner, and some printer drivers ignore it anyway. Where you can, design the print version so that meaning survives without colour: a border plus dark text on the chip, labels on chart bars, patterns instead of hue alone. That is also what WCAG asks for on screens.
@page: size, margins and first pages
The @page rule styles the page box itself, not your elements. You can set its size and margins, and target special pages with pseudo-classes:
@page {
size: A4; /* or letter, or A4 landscape, or 210mm 297mm */
margin: 20mm 18mm;
}
@page :first {
margin-top: 35mm; /* room for a letterhead on page one */
}
@page :left { margin-left: 25mm; } /* wider inner margin for */
@page :right { margin-right: 25mm; } /* double-sided binding */Some honest limits. Inside @page you can only use a small set of properties, mostly margins, size and page-level settings. The user's print dialog can override paper size and margins. The browser's own header and footer (date, page title, URL, page numbers) print in the margin area unless the user switches them off, and you cannot turn them off from CSS directly, although setting @page { margin: 0 } removes the space they would use.
CSS also defines margin boxes such as @top-center and @bottom-right for running headers and footers, with counter(page) for page numbers. Chrome added support for them in late 2024. Firefox and Safari have not followed at the time of writing, so check current support before relying on them in a browser. PDF tools, covered below, are where margin boxes really pay off.
Controlling page breaks
Without guidance, the browser cuts wherever the page area runs out: in the middle of a figure, between a heading and its first paragraph, through a table row. The break properties tell it where cuts are welcome or forbidden:
| Property | Typical use |
|---|---|
break-before: page | Start each chapter or each invoice on a new page |
break-after: avoid | Keep a heading with the content after it |
break-inside: avoid | Keep a figure, card, table row or totals block whole |
orphans: 3 | At least 3 lines of a paragraph stay at the bottom of a page |
widows: 3 | At least 3 lines of a paragraph carry over to the top of the next |
@media print {
h2, h3 { break-after: avoid; }
figure, tr, .totals, .card { break-inside: avoid; }
.chapter { break-before: page; }
p { orphans: 3; widows: 3; }
}Two things trip people up. First, avoid is a request. If a figure is taller than a page, the browser must break it anyway. Second, breaks only work inside normal block flow in most browsers. Content inside a flex or grid container, or anything absolutely positioned, often breaks badly or not at all. This is the strongest reason to switch print to plain block layout with display: block on your main layout containers. You will see older code use page-break-before and page-break-inside. Those are the legacy names. Browsers still accept them as aliases, but write the break-* forms in new code.
orphans and widows are honoured by Chrome and Safari. Firefox has long ignored them, so treat them as an improvement, not a guarantee.
Long tables
Long tables are where print quality is won or lost. Put header rows in a real thead, as the Tables lesson recommended, and Chrome and Firefox repeat it at the top of every printed page, so page four still says which column is which. A tfoot can repeat at the bottom the same way. Safari's behaviour has differed, so test it if your users print from Macs. Add break-inside: avoid on tr so a row is never split across two pages.
With this print stylesheet, which of the three links prints its URL after it? Answer with the link text.
<style media="print">
a[href^="http"]::after { content: " (" attr(href) ")"; }
</style>
<a href="#pricing">Pricing</a>
<a href="/docs/setup">Setup guide</a>
<a href="https://status.example.com">Status page</a>From HTML to PDF
Most PDFs your backend sends (invoices, contracts, reports, tickets) are HTML pages printed by a machine. You pick a renderer:
| Tool | How it works | Good at | Watch out for |
|---|---|---|---|
Playwright or Puppeteer page.pdf() | Drives headless Chromium | Exactly matches Chrome, runs JS, modern CSS | Heavy: a browser per worker, memory, cold starts |
| WeasyPrint | Python library with its own layout engine | Paged media features, margin boxes, page counters, no browser | No JavaScript, its CSS support is not identical to browsers |
| Paged.js | A JavaScript polyfill that paginates in the browser | Margin boxes and running heads inside Chromium | Adds a layer of complexity; check how actively it is maintained |
With Playwright, page.pdf() uses print media by default, so your @media print rules apply. It only works in Chromium.
import { chromium } from "playwright";
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto("http://localhost:3000/invoices/2048/print", { waitUntil: "networkidle" });
await page.pdf({
path: "invoice-2048.pdf",
preferCSSPageSize: true, // respect @page size and margins
printBackground: true, // otherwise backgrounds are dropped, as in a browser
});
await browser.close();WeasyPrint fits Python backends well, because it is a library and needs no browser process:
from weasyprint import HTML
def invoice_pdf(html: str) -> bytes:
return HTML(string=html, base_url="https://app.example.com").write_pdf()@page {
size: A4;
margin: 20mm;
@bottom-right { content: "Page " counter(page) " of " counter(pages); }
}Seniors think about the operations side too. Rendering is slow and memory hungry, so generate PDFs in a background job, not in the request, and store the file. Fonts must be installed in the container or loaded with @font-face, or the PDF falls back to a default font. Images and stylesheets must be reachable from the renderer, which is why base_url matters. And if users can put HTML into a document, sanitise it, because a headless browser that loads attacker-controlled HTML can be pointed at internal URLs.
Why Chrome, Firefox and Safari print the same page differently
Each browser has its own fragmentation code, written at different times. Chromium rewrote its block fragmentation in its LayoutNG engine, which improved breaking inside tables, flex and grid. Firefox has its own paged layout and still ignores orphans and widows. Safari added @page size support later than the others. The print dialogs differ as well: default margins, whether headers and footers are on, and the "background graphics" checkbox. That is why the rule for anything business-critical is to test real print preview in all three, and for PDFs to pick one renderer and pin its version, so output does not shift when the browser updates.
Where print matters at work
- Invoices and receipts. Accountants print them and file them. The total must never split across pages, the company details must appear, and the paid status must survive without colour.
- Résumés and CVs. A portfolio site's résumé page should print to exactly one or two clean pages.
- Recipes, articles and docs. Hide the chrome, print the URLs, keep code blocks whole, and wrap long lines with
white-space: pre-wrapso code is not clipped at the page edge. - Boarding passes and tickets. Barcodes and QR codes must print at full contrast and must not be split.
- Admin dashboards. People print reports for meetings. Charts need
print-color-adjustor labels that do not depend on colour.
Match each print problem to the CSS that fixes it.
Put these steps for adding print support to an existing page in a sensible order.
- Tap the steps below in the right order.
- @media print
- A media query whose rules apply only when the page is printed or rendered to PDF.
- fragmentation
- Splitting laid-out content across page boxes (or columns), deciding where each break falls.
- @page
- An at-rule that styles the page box itself: size, margins, and first, left and right pages.
- break-inside
- A property that, set to avoid, asks the browser not to split an element across pages.
- print-color-adjust
- A property that, set to exact, asks the browser to keep an element's colours and backgrounds when printing.
- margin boxes
- Areas in the page margin, such as @bottom-right, used for running headers, footers and page numbers.
- orphans and widows
- The minimum number of paragraph lines left at the bottom of a page and carried to the top of the next.