Lesson 60 +10 XP

Print Styles

Print styles

When someone prints your page, you can change everything. Save ink and make it look right!

@media print

@media print {
  nav, .advert, .sidebar {
    display: none;           /* hide junk on paper */
  }
  body {
    font-size: 12pt;         /* point p is paper friendly */
    background: #fff;
    color: #000;
  }
}

Remove backgrounds to save ink

@media print {
  * {
    background: none !important;
    color: #000 !important;
  }
}

Page margins

@page controls the page itself:

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

Break control

Keep elements together when printing:

h2 { break-after: avoid; }
table { break-inside: avoid; }

Show URLs for links

Make printed links print their target:

@media print {
  a::after {
    content: " (" attr(href) ")";
  }
}

TL;DR

  • @media print targets printed output.
  • Hide navs and ads, force black on white.
  • Use pt for paper sizes.
  • @page styles margins/size.
  • Prevent awkward breaks with break-inside: avoid.