CodeBlanks Logo Icon CodeBlanks

Print media

CSS course · Advanced · Lesson 39/52

Learn print styles with @media print.

The @media print block

To write styles only for print, wrap them in an @media print block. The declarations inside take effect only in the print dialog; the on-screen layout is untouched.

A common case is hiding the navigation when printing. Write @media print { nav { display: none; } }. The report prints clean; on screen, the nav still shows.

Hiding elements in print

To drop unneeded elements from print, use display: none. @media print { .ad-banner { display: none; } } keeps the ad banner off the paper. Navigation, footers, and form buttons can be hidden the same way.

You could use visibility: hidden instead, but it keeps the element's space. For print, display: none is usually preferred.

Printing link addresses

If you want to show link addresses in print, the a::after selector and the content property help. @media print { a::after { content: " (" attr(href) ")"; } } appends each link's address in parentheses.

Do this only inside @media print; otherwise every on-screen link gets its address tacked on. Print readers can then see where links go.

Exercise Hide the nav bar when printing

Write an @media print block. Inside it, declare display: none for the nav selector. The nav block must sit inside the @media print block.

Show example solution
/* hide nav in print */
@media print {
  nav {
    display: none;
  }
}

Test yourself

  1. When is the @media print block active?

    • Only on screen
    • Only in the print dialog
    • Both on screen and when printing
    • Only on mobile devices
    Show answer

    Only in the print dialog — Correct. The @media print block is active only in the print dialog.

  2. Hide the ad in print

    @media print {
      .ad-banner { ____: none; }
    }
    
    Show answer
    @media print {
      .ad-banner { display: none; }
    }
    
  3. Match each piece to its meaning

    @media print
    Print block
    display: none
    Hides element
    visibility: hidden
    Hides but keeps space

All lessons in Advanced