CSS Print · Astro Tech Blog

CSS can create styles specifically for printed pages using the print media type.

Demo: Print Style Sheet (Simulated)
HTML
<div class="print-preview">
<header class="no-print">Header (hidden in print)</header>
<main>
<h1>Article Title</h1>
<p>This content appears in print.</p>
</main>
<aside class="no-print">Sidebar (hidden in print)</aside>
<footer>Footer (visible in print)</footer>
</div>
CSS
@media print {
.no-print { display: none; }
body { font-size: 12pt; color: black; background: white; }
a::after { content: " (" attr(href) ")"; font-size: 0.8em; }
@page { margin: 2cm; }
}
.print-preview { font-family: Georgia, serif; max-width: 600px; }
header, footer, aside { padding: 10px; margin: 4px 0; border: 1px solid #cbd5e1; border-radius: 4px; }
header { background: #eef2ff; }
footer { background: #f1f5f9; }
aside { background: #fef9c3; }
Live Output Window

Common Print Techniques

@media print {
  /* Hide non-essential elements */
  nav, .sidebar, .advertisement { display: none; }

  /* Make links visible */
  a[href]::after {
    content: " (" attr(href) ")";
  }

  /* Page breaks */
  h2 { page-break-before: always; }

  /* Ensure backgrounds appear */
  * {
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
  }
}

@page Rule

Control the printed page dimensions and margins:

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

@page :first {
  margin-top: 4cm;
}
PropertyWhat It Does
page-break-beforeBreak before an element (always, avoid)
page-break-afterBreak after an element
page-break-insideAvoid breaks inside an element
orphansMin lines at bottom of page
widowsMin lines at top of page

Always test your print styles — what looks good on screen may not translate well to paper.