Sub topic 14
Print styles
This chapter assumes you know basic media query syntax (@media and the and operator), CSS selectors, and the cascade. It covers how to restyle a page for paper or PDF output.
Media types
A media query can start with a media type. The type says what kind of output the styles are for. The ones you will use are:
| Type | Applies when |
|---|---|
| `all` | Always. This is the default when you omit a type. |
| `screen` | The page is shown on a display. |
| `print` | The page is printed, or the browser shows a print preview or saves a PDF. |
Most of your stylesheet needs no type. You add a print block only for the differences between screen and paper.
A basic print block
Navigation, ads, and other interactive parts are useless on paper. Hide them, and use plain black text on a white background to save ink.
@media print {
nav,
.ads {
display: none;
}
body {
color: #000;
background: #fff;
}
}Browsers usually drop background colors and images when printing, unless the user turns on "background graphics". Do not rely on a background to carry meaning, such as a dark banner behind white text. Without the background, the white text disappears.
Print-specific adjustments
Paper has fixed pages, so you control where content breaks. You can also show information that only matters on paper, such as where a link points.
@media print {
a[href^="http"]::after {
content: " (" attr(href) ")";
font-size: 0.9em;
}
h2,
h3 {
break-after: avoid;
}
figure,
tr {
break-inside: avoid;
}
}The first rule appends the address after each external link, because a reader can't click a printed link. The break-after: avoid rule keeps a heading from ending up alone at the bottom of a page. The break-inside: avoid rule keeps a figure or table row on one page where possible.
Lengths work differently in print. Use pt or cm for page-related sizing, and avoid vw and vh. These units refer to the page area during printing, so results vary between browsers.
Testing print styles
You don't need to print to check your work. In Chrome or Edge DevTools, open the Rendering panel and set "Emulate CSS media type" to print. Firefox has a print-simulation button in the Inspector. Opening the browser's print preview (Ctrl+P or Cmd+P) shows the real page breaks, which emulation does not.
Common errors
- Hiding content with
display: nonethat the reader needs, such as the article's author or date. Hide only chrome, not content. - Forgetting that link colors and underlines are lost in black-and-white printing. Keep links underlined.
- Testing only in one browser. Page-break support differs, so check the print preview in at least two.
Exercise
Write a print rule that hides the element with class .comments and stops every blockquote from splitting across two pages.
Show answer
@media print { .comments { display: none; } blockquote { break-inside: avoid; } }