Different CSS style rules for printing
Posted May 26th, 2010 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:
- CSS background transparency that doesn't affect the text on top (Wednesday, May 12th 2010)
- Change element's properties with CSS based on body id or class (Thursday, May 6th 2010)
- "Clearing" floats with overflow: auto (Saturday, January 9th 2010)
- Using ellipsis with HTML and CSS (Saturday, December 5th 2009)
- Multiple CSS classes for a single element (Saturday, March 21st 2009)
- Using !important with CSS (Saturday, January 31st 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
