Printer Only Formatting Using CSS

Posted by

While browsers can handle the translation from web page to printer paper, you can also tweak the print view to best fit your needs. One of the reasons you might want to do this is to create a “print friendly” display of what is on the page, or if you have a page that would be frequently printed. One of the advantages is defining page breaks. Maybe you even want a header or footer repeated on every page printed out.

Creating a view of a webpage that’s specific to the print functionality is actually pretty easy. When CSS2 was released, it included a @media tag to define these sorts of things. Full reference can be found here, but we’re going to focus on the print mediatype. This mediatype is utilized when the print dialog is triggered from the browser (typically “Ctrl-P”, from the menu of the browser, or you can trigger it with javascript using “window.print();”).

We wrap the styles we want to define with our @media print { }, and can define our desired page breaks, and repeat headers with the following code:

@media all { 
    .page-break  { display: none; } 
    .header { display: none; } 
    .header:first-of-type { 
        display:block; 
    } 
} 
 
@media print { 
    .page-break  { display: block; page-break-before: always; } 
    .header { display: block; } 
} 

The strategy is to define how the page will look normally, so we explicitly say that we only want to display the first header by default, but when we are in the print mediatype, we redefine the display of these headers to always display. It’s important to note that the actual HTML for the header will need to be repeated on each page (which can be done manually, or by ways of looped code like Angular’s ng-repeat). Additionally, we define our page-break class with attribute “page-break-before: always;”. This allows us to manually define page breaks in our code as a div with that class.

Working example can be found here: https://rawgit.com/mvalenta/blog-css-examples/master/PrintViewCss.html

Remember that the view changes only when you attempt to print, Ctrl-P

Example raw code can be found here: https://github.com/mvalenta/blog-css-examples/blob/master/PrintViewCss.html

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.