Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 139 ยท Best Practices

Print Styles

Make web pages print well with @media print, hide screen-only parts, show link URLs, control page breaks and set page margins and size with @page.

People still print web pages. They print recipes for the kitchen, boarding passes, invoices, tickets, articles to read on the train, and documentation to mark up with a pen. Even more often, they "print" to PDF to save or share a page. Without print styles, they get the navigation bar, a cookie banner, a dark background that eats ink, and links that are just underlined words on paper.

CSS has dedicated tools for this. In this lesson you will write a print stylesheet with @media print, hide what doesn't belong on paper, reveal link URLs, control where pages break, and set page size and margins with @page. Because the live previews can't open a print dialog, each demo has a button that applies the print styles on screen so you can see the effect.

Adding print styles

There are two common ways to add print-only CSS. Inside your main stylesheet, use a media query:

CSS
@media print {
  .site-nav,
  .sidebar,
  .cookie-banner {
    display: none;
  }
}

Or keep them in a separate file linked with a media attribute:

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

A separate file with media="print" doesn't block rendering on screen, as you saw in CSS Performance. For a small number of rules, a block at the end of your main stylesheet is simpler.

You can preview print styles without wasting paper. Open DevTools, find the Rendering panel and set "Emulate CSS media type" to print. Or use your browser's print preview, which also shows page breaks.

How the demos work

The editor can't show a print preview, so the demos below put the print rules behind a .print class on the html element. A button toggles that class. In your own site, you would write the same rules inside @media print { } instead of prefixing them with .print.

What a print stylesheet usually does

Most print stylesheets make the same handful of changes:

  • Hide screen-only parts: navigation, sidebars, search, buttons, video players, chat widgets and ads.
  • Use black text on white. Dark themes and colored backgrounds waste ink and often print poorly. Browsers drop backgrounds by default anyway.
  • Widen the content. Remove max-width limits, side columns and large margins; the page margin is enough.
  • Use print-friendly units. pt is natural for type on paper: 11pt or 12pt body text reads well.
  • Reveal hidden information, such as link URLs and the meaning of abbreviations.
A page and its print version

Switch to the print version. The navigation, sidebar and share button disappear, the dark header becomes a simple title with a rule beneath it, and the text switches to a serif typeface sized in points. On a real site, the button itself would be hidden too.

On paper, "see our guide to dried beans" is useless if the reader can't see where the link goes. Generated content can print the URL right after the link text, using attr():

CSS
@media print {
  a[href^="http"]::after {
    content: " (" attr(href) ")";
    font-size: 0.85em;
    word-break: break-all;
  }

  abbr[title]::after {
    content: " (" attr(title) ")";
  }
}

The selector a[href^="http"] only matches absolute URLs, so in-page links like #top or javascript: links don't get noisy suffixes. If your site uses relative links such as /recipes/chili, print the full address with a prefix: content: " (https://example.com" attr(href) ")". See Attribute Selectors and Pseudo-elements for the building blocks.

Printing URLs and abbreviations

The external link gains its URL and the abbreviation gains its full name, but the #top link stays clean.

Controlling page breaks

Paper is split into pages, and you get a say in where the splits fall. These properties take effect when content is broken across pages (and, conveniently, across columns):

  • break-before: page starts an element on a new page. Good for chapters or each invoice in a batch.
  • break-after: page forces a break after an element.
  • break-inside: avoid keeps an element in one piece if it fits on a page: tables, figures, cards, code blocks.
  • break-after: avoid on headings keeps a heading from being stranded at the bottom of a page, away from its text.
  • orphans and widows set the minimum number of lines of a paragraph left at the bottom of a page (orphans) or carried to the top of the next (widows). Both default to 2.
CSS
@media print {
  h2 { break-before: page; }
  h2, h3 { break-after: avoid; }
  figure, table, pre, .card { break-inside: avoid; }
  p { orphans: 3; widows: 3; }
}

You may also meet the older names page-break-before, page-break-after and page-break-inside. Browsers still accept them as aliases, but use the break-* versions in new code.

Since the preview can't paginate, the next demo uses CSS columns. Column breaks follow the very same break-inside rule, so you can watch it work.

break-inside: avoid in action

Without the rule, one card is sliced in half across the two columns. Tick the box and the card moves to the next column whole. On paper, the same rule moves it to the next page.

Fragmentation in depth

When a box is too tall for the space it lands in, the browser splits it into pieces called fragments. The space can be a printed page, a column in a multi-column layout, or a region. The splitting process is called fragmentation, and one set of properties controls all of it. That is why the column demo above is a fair stand-in for paper: the same rules apply.

break-before, break-after and break-inside

break-before and break-after describe what should happen at the edge between two boxes. break-inside says whether the box may be cut open. The values you will actually use:

Value Meaning
auto No preference (the default): break when space runs out
avoid Avoid a break here, in any kind of container
avoid-page, avoid-column Avoid a break only when the container is a page, or only a column
page Force a break so the next content starts on a new page
left, right Force break(s) so the next page is a left or right page, inserting a blank page if needed
recto, verso Like right and left, but follow the reading direction (newer, so check support)
column Force a break so the next content starts in a new column

The values fall into two kinds. Forced breaks (page, left, right, column) are commands, and the browser always obeys them. Avoid values are requests: the browser honors them when it can, and ignores them when honoring them would make a fragment impossibly tall, for instance a table taller than a page.

A few guidelines keep the results predictable:

  • Breaks happen between siblings. A break-before: page on the very first element of the document doesn't create a blank first page.
  • Put page-oriented rules inside @media print, because on screen break-before: page has no visible effect, except inside columns.
  • Table rows are the most common place to need break-inside: avoid. Set tr { break-inside: avoid; }, and keep the header in a <thead> (displayed as table-header-group) so printers repeat it on every page.
CSS
@media print {
  .chapter { break-before: page; }          /* each chapter on a new page */
  .chapter:first-child { break-before: auto; }
  h2, h3 { break-after: avoid; }            /* a heading never ends a page */
  figure, tr, pre, blockquote { break-inside: avoid; }
  .appendix { break-before: right; }        /* the appendix opens on a right-hand page */
}

box-decoration-break: what happens to borders and padding

When a box is split, what should the fragments look like? By default (slice), the browser lays the box out as if it were one piece and then slices it. Padding, borders, border radius and shadows appear only at the very start and the very end. A highlighted phrase that wraps onto a second line loses its right padding on line one and its left padding on line two. The same happens when a card is cut by a column or page break.

box-decoration-break: clone gives every fragment its own decorations, as if each were a separate box:

CSS
mark {
  padding: 0.1em 0.4em;
  border-radius: 0.4em;
  -webkit-box-decoration-break: clone;   /* older Chromium and Safari */
  box-decoration-break: clone;
}

It is useful for inline highlights, tags and pills that wrap, and for cards that may be split across columns or pages, because each piece then looks like a complete card.

slice versus clone on a wrapping highlight

With the option off, the highlight is one continuous slab: only its first line has a rounded left end and only its last line a rounded right end. With it on, every line gets padding and rounded ends of its own.

orphans and widows

These two apply to paragraphs that get split. orphans is the minimum number of lines that must stay at the bottom of the first fragment, and widows is the minimum that must be carried over to the next. They default to 2, which already prevents a single stranded line. Raise them for body text when you want calmer pages, but note that large values pull whole paragraphs along and can leave gaps.

They count lines of inline content in a block, so they have no effect on a tall image or a table. Browsers that fragment columns honor them too, which means you can test them without printing.

Orphans and widows in two short columns

With the stricter rule off (both values are 1), the second paragraph leaves a single line at the bottom of the first column. Switch it on and that lonely line moves: because the paragraph can't put three lines in the first column, the whole paragraph starts in the second one. That is the trade-off of large values, a little unused space in exchange for no stranded lines.

Columns and print together

Multi-column layouts and pages nest: the browser first fills a page's columns, then starts the next page. That means a rule such as break-inside: avoid on a card protects it from both kinds of cut at once, so one declaration is often enough for a card grid that shows in columns on screen and prints to paper. Use column-span: all for headings that should stretch across every column, break-before: column to start a new column on purpose, and leave column-fill at its default (balance) to even out the columns on the last page.

The @page rule

@page styles the page box itself: its size, its margins and, in supporting browsers, the content in its margins.

CSS
@page {
  size: A4;            /* or letter, A5, "210mm 297mm", landscape */
  margin: 2cm 1.5cm;
}

@page :first {
  margin-top: 4cm;     /* extra room on the first page */
}

@page :left  { margin-left: 2.5cm; }   /* for double-sided printing */
@page :right { margin-right: 2.5cm; }

A few things to know:

  • Margins: margin in @page is the most reliable part and works in all major browsers. Use physical units like cm, mm, in or pt.
  • Size: size is honored by Chromium-based browsers and Firefox, and is a strong hint elsewhere. The user can always choose a different paper size in the print dialog.
  • Margin boxes: rules such as @top-center { content: "Field Guide"; } and page numbers with counter(page) are part of the standard, but browser support is still incomplete. Treat them as a bonus, not a requirement.
  • Browser headers: the date, title and URL printed in the corners come from the browser's print settings. Users can turn them off; CSS can't fully control them.

Colors and backgrounds

By default, browsers skip background colors and images when printing to save ink. Usually that's what you want. When a background carries meaning, such as a colored status badge, a chart or a highlighted row, you can ask the browser to keep it:

CSS
@media print {
  .status-badge,
  .chart {
    print-color-adjust: exact;
  }
}

print-color-adjust: exact is a request, not a guarantee: the user's "background graphics" setting can still win. Older Chromium and Safari versions only knew the prefixed -webkit-print-color-adjust, so many stylesheets declare both. Better still, don't rely on color alone. A border or a text label prints in every case.

A starter print stylesheet

Here is a compact starting point you can adapt:

CSS
@media print {
  @page { margin: 1.5cm; }

  body {
    font: 11pt/1.5 Georgia, "Times New Roman", serif;
    color: black;
    background: white;
  }

  nav, aside, footer, form, video, .no-print { display: none !important; }

  main, article { width: auto; max-width: none; margin: 0; padding: 0; }

  a { color: black; }
  a[href^="http"]::after { content: " (" attr(href) ")"; font-size: 0.85em; }

  h1, h2, h3 { break-after: avoid; }
  img, figure, table, pre, blockquote { break-inside: avoid; }
  img { max-width: 100% !important; }
  p { orphans: 3; widows: 3; }
}

A .no-print utility (and its opposite, a .print-only class that is display: none on screen) gives authors a quick way to fine-tune individual pages.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which rule hides the site navigation only when printing?

    @media print applies its rules only when the page is printed or saved as PDF.
  2. 2. What does a[href^="http"]::after { content: " (" attr(href) ")"; } do in a print stylesheet?

    attr(href) inserts the link's address, and ^="http" limits it to absolute URLs.
  3. 3. Which property keeps a figure from being split across two pages?

    break-inside: avoid asks the browser to keep the element in one piece if it fits on a page.
  4. 4. What is the most widely supported part of the @page rule?

    @page { margin: ... } works in all major browsers; margin boxes and page counters have incomplete support.
  5. 5. Why might a colored badge disappear when printed, and what helps?

    Browsers drop backgrounds to save ink. print-color-adjust: exact asks to keep them, and a border or label works regardless.

Summary

  • Use @media print or a <link media="print"> stylesheet; preview with DevTools print emulation.
  • Hide screen-only parts, use black on white, remove width limits and size text in pt.
  • Reveal link URLs and abbreviation titles with ::after and attr().
  • Control pagination with break-before, break-after, break-inside, orphans and widows.
  • Fragmentation rules (break-*, orphans, widows) work the same in columns and on paper; box-decoration-break: clone gives each fragment its own padding, borders and radius.
  • @page sets page margins (well supported) and size; margin boxes are still patchy.
  • Backgrounds are dropped by default; print-color-adjust: exact asks to keep important ones.

Next: CSS At-rules Overview.