Print stylesheets

Intermediate · 16 min

How @media print and @page turn a web page into a clean printed or PDF document: hiding chrome, link URLs, page breaks, paper size, margins and testing.

Before thisCSS performanceMedia Queries and Mobile-First

freeCodeCamp.org · 16 min

Print stylesheets

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by freeCodeCamp.orgReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Printing is just another medium. `@media print { ... }` applies only when the page is printed or saved as PDF, and the rest of your CSS still applies unless you override it.
  • A good print stylesheet removes what has no use on paper (navigation, ads, buttons, video), drops dark backgrounds, sets text to black on white, and lets content use the full page width.
  • `a[href^="http"]::after { content: " (" attr(href) ")"; }` prints the address after each external link, because a printed link cannot be clicked.
  • `@page` sets paper size, orientation and margins. `break-inside: avoid`, `break-before` and `break-after` control where content may split between pages.
  • Browsers do not print background colours and images by default. `print-color-adjust: exact` asks for them, but design for the default.

Why a print stylesheet at all

People still print receipts, tickets, recipes, invoices, boarding passes and documentation, or save them as PDFs, which uses the same machinery. A page not designed for it produces a printout with a navigation bar across the top, a cookie banner, a dark background that turns into a grey wash, and a table cut off at the right edge. A few dozen lines of CSS fix most of that.

The key idea is the one from media queries: screen and print are media types, and print is just another place your CSS gets applied. Your screen CSS also applies when printing, unless you override it, so a print stylesheet is mostly a list of overrides.

Two ways to write it

Inline, with a media query:

@media print {
  nav, footer, .cookie-banner, video { display: none; }
}

Or as a separate file:

<link rel="stylesheet" href="print.css" media="print">

The file version has a performance benefit: a stylesheet whose media does not match is not render-blocking, so it does not delay the screen display. The CSS performance lesson covers that.

A starting point

@page { size: A4; margin: 2cm; }

@media print {
  html { font-size: 12pt; }
  body { color: #000; background: #fff; }

  /* Remove what is useless on paper */
  nav, aside, footer, .ad, .cookie-banner, video, button { display: none; }

  /* Use the whole page */
  main { max-width: none; margin: 0; padding: 0; }

  /* Links cannot be clicked, so show where they go */
  a { color: inherit; text-decoration: underline; }
  a[href^="http"]::after { content: " (" attr(href) ")"; font-size: 0.85em; }

  /* Keep things together */
  h1, h2, h3 { break-after: avoid; }
  img, figure, pre, blockquote, tr { break-inside: avoid; }
  thead { display: table-header-group; }
}

A walk through the parts:

  • Units. Print uses physical units: pt, cm, mm, in. Body text around 11 to 12pt is typical. px still works but means 1/96th of an inch.
  • Colours. Black text on white saves ink and reads better. Link colours rarely survive in black and white, so underline links.
  • Hide chrome. Navigation, ads, forms and video are noise. display: none is fine here, since print is a separate medium.
  • Use the width. Screen layouts often cap line length, centre columns and add sticky sidebars. Reset them.
  • Generated content. attr(href) in content writes the link target into the page. Restrict to http links so same-page anchors and mailto: do not clutter.

@page: paper, orientation and margins

@page { size: A4 portrait; margin: 2cm; }
@page :first { margin-top: 4cm; }

@page sets the paper size, orientation and margins for the printed page box, which the web page flows into. I ran Chrome’s headless --print-to-pdf on a test page with @page { size: A5; margin: 15mm; } and the resulting PDF’s page box was 420 by 595 points, which is A5, so the size was honoured. Browser support varies for the finer details: margin boxes (headers and page numbers with @top-center and counter(page)) are newer and less widely supported, and browsers’ print dialogs can override size and margins. Treat @page as a strong preference, not a guarantee.

Controlling page breaks

When content flows past the end of a page, the browser breaks it somewhere. You can guide where:

  • break-inside: avoid keeps a block (a figure, a table row, a card) whole.
  • break-before: page and break-after: page force a new page, for example before each chapter heading.
  • break-after: avoid on headings keeps them with the paragraph that follows.
  • orphans and widows set the minimum lines left at the bottom or carried to the top of a page.

The older page-break-before, page-break-after and page-break-inside are legacy aliases that still work, and they appear in many tutorials, but the break-* versions are current. Break control is patchier inside multi-column text and flex or grid containers, so test the real output.

Backgrounds and images

Browsers skip background colours and images when printing, to save ink. Text that is white on a dark background then prints as white on white. Two answers: override to dark text on white in the print stylesheet, which also saves ink, or opt in for things that need their background, such as a status badge:

.badge { print-color-adjust: exact; }

print-color-adjust is in Chrome 136 and Firefox 97 and Safari 15.4 according to MDN’s compatibility data; older Chrome versions only understood the prefixed -webkit-print-color-adjust, so writing both is common. The user’s print settings can still turn background printing off.

Images print fine, but large full-bleed photos waste ink and pages, so cap them with max-width: 100% and consider hiding purely decorative ones.

Testing without wasting paper

  • DevTools: the Rendering tab has “Emulate CSS media type: print”. The page re-renders in print mode and you inspect it normally. Debugging CSS with DevTools covers where to find it.
  • Print preview: Ctrl/Cmd+P shows the paginated result, including @page size and breaks.
  • Headless PDF: chrome --headless --print-to-pdf=out.pdf page.html is good for automated checks and for generating PDFs from HTML templates.

Also check the result in at least one other browser, since pagination differs between engines.

What the video covers

freeCodeCamp’s “Print Styles: CSS Tutorial (Day 6 of CSS3 in 30 Days)” (September 2018, about 16 minutes) is described as showing how to create a print stylesheet, a page styled to look best on paper. It is part of a series by Brad Hussey, and the description says it works as a stand-alone tutorial. The downloadable files it uses are hosted on Dropbox, which may not stay available. It is from 2018, so it may use the legacy page-break-* properties; break-* is current. I could not read a transcript, so its examples are not described here, and the sections on @page, print-color-adjust and testing come from the documentation and my own runs. I did not find a better print-focused English video, so this is the one pick.

Where this fits

Print is the last stop for the CSS roadmap, and it uses the media-query idea from media queries and mobile-first and the loading advice from CSS performance. If you reached here from the beginning, how CSS works and where it lives is the place to revisit with fresh eyes.

Check yourself

  1. 01How do you hide a site's navigation and footer only when the page is printed?

    `@media print { nav, footer { display: none; } }`, in your stylesheet or a separate file loaded with `<link rel="stylesheet" href="print.css" media="print">`. A `media="print"` link does not block rendering on screen.

  2. 02Why print the URL after each external link, and how?

    A reader of a printed page cannot click, so the destination is lost. `a[href^="http"]::after { content: " (" attr(href) ")"; }` adds the address from the `href` attribute after the link text. Limit it to external links so internal anchors and long tracking URLs do not clutter the page.

  3. 03You have a table that splits across two pages and loses its header row on the second. What helps?

    Make the header a `<thead>` and give it `display: table-header-group`, which browsers repeat on each printed page. For rows that should not be cut in half, add `tr { break-inside: avoid; }`.

  4. 04A card's dark background shows on screen but the printout is white with white text. What happened and what are the options?

    By default browsers skip background colours and images to save ink, leaving the text colour you set, white. Either override colours in `@media print` so the printout uses dark text on white, or add `print-color-adjust: exact` on the element to ask the browser to print its backgrounds.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark