Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add print styles

Short answer

Rules inside @media print apply only when printing. Hide everything that is not needed on paper:

<style>
  @media print {
    nav, .no-print { display: none; }
    body { color: black; background: white; }
  }
</style>
 
<nav>Menu: Home · Blog</nav>
<h2>Pancake recipe</h2>
<p>Mix flour, eggs and milk.</p>
<button class="no-print" onclick="print()">Print</button>

Press "Print" and look at the preview: the menu and the button are not there.

A link cannot be clicked on paper. Print its address after the text:

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

Page breaks

break-before: page starts an element on a new page, and break-inside: avoid keeps a block — an image with a caption or a table row — from being split between two sheets:

@media print {
  h2 { break-before: page; }
  figure, tr { break-inside: avoid; }
}

Common mistake

A site with a dark theme or a colored background is printed as is. Most browsers do not print backgrounds by default, and light text stays almost invisible on white paper. Set a dark text color for print explicitly, as in the first example.

Functions used in this recipe

  • @media — Applies rules only under given conditions — the window width, the system theme and others.
  • display — Decides how an element behaves in the flow and how it lays out its content.
  • content — The content of the `::before` and `::after` pseudo-elements.
  • href — The address an `<a>` link leads to or a `<link>` points at.

Thanks for reading!

Donate to the site — we work hard for you.