Using CSS3 to make your web pages better when they are printed.


I recently walked past someone in the office who was reading a web article that they’d printed off. Now putting to one-side the environmental impact of printing the internet there is also another disadvantage to reading printed webpages… the hyperlinks don’t work. Wouldn’t it be nice if you could somehow add the textual link next to a hyperlink but only when a document was printed, well you can using CSS :after selector.

Demo view here

Firstly you will need to add a print style sheet. This is just a regular stylesheet which is only applied when the document is being printed. This requires a regular style sheet link with the attribute media=”print”.

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

Inside this style you just need to the following CSS. I tend to switch text decoration (the underlining) off of printed hyperlinks because it’s easier to see URL when they are printed without the underlining (but this is entirely optional and there are reasons why you might not want to do this)

a:after
{
    content: " (" attr(href) ")";
}
a
{
    text-decoration: none;
}

The demo page will then look like the below image when it is printed:

An image of the printed webpage

If you would rather use inline style then you could write it like this:

<style>
        @media print
        {
            a:after
            {
                content: " (" attr(href) ")";
            }
            a
            {
                text-decoration: none;
            }        
        }
</style>
Comments (3)

  1. norgie says:

    Neat little "trick".

    Thanks for posting.

  2. Mark J Smith says:

    I think you should be using ::after instead of :after because it's a pseudo-element. Single colon is defined as a pseudo-class and double as a pseudo-element but they left :before and :after working in browsers for backwards compatibility from before this definition had been set.

Skip to main content