Different CSS style rules for printing

Posted in HTML and CSS -

This post looks at how to specify different CSS style rules for printing: using a secondary style sheet for print only, or defining the print styles in the main style sheet using @media print.

The default style sheet and print style sheet

When printing, the default style sheet will be used and if a specific print style sheet or style rules have been created then those will be applied as well. It is important to keep the rules in the correct order so ensure you default styles are declared first (or when using external style sheets the file is <link>d or @imported first) and the print ones second.

Using a secondary style sheet with <link>

Let's say all the styles for the website were in the file /css/main.css and the modified and additional styles for print were in /css/print.css. Then using <link> tags to add the style sheets to the page do this:

<link href="/css/main.css" rel="stylesheet" type="text/css" />
<link href="/css/print.css" rel="stylesheet" type="text/css" 
media="print" />

The part that makes the second one a print style sheet is the media="print" part.

Using a secondary style sheet with @import

If you use @import you can again specify the media type and make a CSS file used just for printing. Using the same two style sheets as in the first example, do this:

<style type="text/css">
  @import url("/css/main.css");
  @import url("/css/print.css") print;
</style>

In this case, it's "print" at the end of the second @import which makes it the print style sheet.

Using @media print in the common CSS file

The print rules can also be set using "@media print" in your main/common CSS file (or even in the <style> block, but you wouldn't normally do that) like so:

@media print {
  .. style rules here...
}


Related posts:


Comments