Printer Friendly Links Using CSS

I have been looking at ways to improve the printer friendly version of my site lately.

Once printed, URLs of links aren't printed, and sometimes that's not a good thing.

I was thinking about listing all the URLs at the end of page and hiding them with by turning off their visability on the master CSS file, and only having them visable using the print CSS file.

However, I came across an interesting article on A List Apart called Going To Print. This suggested using the power of CSS2 and CSS3 to show the URL as part of the link. For example, a this link...

A List Apart

would become...

A List Apart (http://www.alistapart.com/)

Mozilla based browsers such as Firefox implement CSS2 and some of the CSS3 recommendation specification. Unfortunately Microsoft's Internet Explorer doesn't, so this won't for users wanting to print from that particular browser.

To add the URL after the link text, we have to use the CSS2 pseudo-element selector :after. For printer friendly version of my site, I only want links that are part of the mainbody class to be expanded.

.mainbody a:link:after, .mainbody a:visited:after { content: " (" attr(href) ") "; font-size: 80%; font-family: Courier, sans-serif; }

Here I'm making sure any visted or unvisited links are treated equally when being selected by the stylesheet. I'm adding the value of the href attribute, surrounded by brackets, to the content of the element. I'm also using a fixed width font and shrinking the text size down a bit.

This is fine, but unfortunately if I use relative links on the page it gives me results like

Rob's Blog (/robblog/)

instead of

Rob's Blog (http://www.robertprice.co.uk/robblog/).

This is where CSS3 comes to the rescue. We can use a conditional attribute selector to see if the href attribute starts with /. If it does we know it's a relative link and we want to prefix the URL with http://www.robertprice.co.uk. We do this using the following bit of CSS.

.mainbody a[href^="/"]:after { content: " (http://www.robertprice.co.uk" attr(href) ") "; }

The downside of using CSS3 is that it is not a finalised standard, and as a result breaks the W3C's CSS Validator.

We can put this in a printer only stylesheet using HTML like this, ensuring the media attribute is set to print

<link rel="stylesheet" href="/includes/printstyle.css" type="text/css" media="print" title="printer stylesheet" />
Entered: 2004-09-03 14:02:38
Modified: 2004-09-03 14:06:38

Rob's Other Blog Entries

See other blog entries for September 2004, or an index of all blog entries.