CSS for Printing

Conditional Styling

We can define CSS that only acts conditionally. Those conditions can be specified in several ways. Also we can either link to multiple CSS files or we can build the conditional statements into a single CSS file.

The CSS link we've used all semester can handle some of this. We can add a media attribute with the values screen, print, or handheld. Whatever media is used will determine the CSS file utilized. Unfortunately Apple devices ignore the handheld attribute so we cannot use this for responsive design. However, the print attribute is usable.

link rel="stylesheet" href="printfile.css" media="print"

Try using a print preview now!

The Code

This effect is pretty simple to create. I have two CSS files linked to the HTML file, like so:

link rel="stylesheet" href="style.css"  
link rel="stylesheet" href="printstyle.css" media="print"

The first file contains my normal CSS coding. In this example I've created a border around the figure, added some padding, centered the caption, and made the caption text italic. The code looks like this:

figure {border: solid thin black;  
width: 640px;  
padding: 5px;}

figcaption {text-align: center;  
font-style: italic;}

In the printstyle.css file, I change the formatting to hide anything I do not want to print. In this case, the code is:

figure {display: none;}

Since figcaption is contained within figure, I do not need to address that element.

This approach can be used to hide anything: classes, IDs, elements, etc.

Alley Spring Mill
Alley Spring Mill

Printing urls After Hyperlinks

This is a neat but rarely used approach. Look at the following hyperlink.

UTMartin

Now see what happens during a print preview!

I simply added the following code to the printstyle css sheet. This is another pseudo-element!

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

Page Breaks

You can also force a page break rather easily. I added the following code to the printstyle css sheet and applied the class where I wanted the page break to occur. Please note this does not work reliably in Chrome (there are multiple possible causes!).

.newpage {page-break-before: always;}