@media print

Pages that print well

Lesson 18 of 20 · 9 min · Module 5: Pages for every situation

People still print recipes, cheat sheets, tickets and invoices, or save them as PDF. A short print stylesheet removes navigation and buttons, uses black text on white, and shows where links lead.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Write rules that apply only when printing
  • Hide interface elements on paper
  • Show link addresses and control page breaks

The idea

Rules inside @media print { … } apply only when printing or saving as PDF. Hide interface parts with display: none, and add the address after external links with a[href^="http"]::after { content: " (" attr(href) ")"; }. break-after: avoid keeps a heading on the same page as the text that follows it.

@media print {
  .sidebar { display: none; }
  body { font-size: 12pt; }
}

01A separate medium

@media print applies when someone prints or saves as PDF. The screen design stays untouched, so you can simplify freely.

02Paper cannot click

A printed link is just underlined text. attr(href) inserts the link’s address into the page, so readers can still find the source.

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

03Sensible page breaks

break-after: avoid on headings and break-inside: avoid on figures, cards and table rows prevent awkward splits, such as a heading alone at the bottom of a page.

Your turn

Add @media print with: nav and .no-print set to display: none; body with color: #000000 and background: #ffffff; a[href^="http"]::after { content: " (" attr(href) ")"; }; and h2 { break-after: avoid; }. On screen, nothing changes.

What the checks look for

  • Navigation is hidden on paper
  • Buttons marked .no-print are hidden on paper
  • Printed text is black
  • External links show their address
  • Headings stay with their text
  • On screen the navigation is still visible
Try it in the editor →

Take this with you

A few print rules turn any page into a clean document.

Go a little further

Add @page { margin: 2cm; } inside the print styles to set the paper margins.

Learn HTML & CSS Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →