Digital Web Magazine

The web professional's online magazine of choice.

CSS Styling for Print and Other Media

Got something to say?

Share your comments on this topic with other web professionals

In: Articles

By Ian Lloyd

Published on November 20, 2006

Note: This excerpt from the upcoming book “Pro CSS Techniques” by Jeff Croft, Ian Lloyd, and Dan Rubin, has been edited for this publication with permission of the chapter’s author, Ian Lloyd. The excerpt is approximately two-thirds of the length of the original chapter.

There are many different media types that you can apply to CSS, some of which are more useful than others, and they let you specify the look, feel, or sound of the web page that is linked to the CSS files. In this section, we’ll look at the various media types that are available (as gleaned from the official source, namely the W3C: www.w3.org/TR/REC-CSS2/media.html#q1). However, rather than list them all and suggest wonderfully practical ways to use them, we’ll break the list down into two categories: useful and not-so-useful (read: which ones you’re likely to use on a day-to-day basis in the foreseeable future, and those that you won’t touch in a month of Sundays).

The Useful Media Types

This list includes the media types that you will truly find a use for on regular occasions:

We’ll be using (or covering briefly) these media types in this chapter’s examples.

The Not-So-Useful Media Types

Remember what I was saying about those media types that you’d never use in a month of Sundays? Well, here they are, listed for your soon-to-be-ignored pleasure:

We won’t focus on these types because, while the reasoning behind them is good, support for their usage may be nonexistent. However, we’ll expand on the aural and handheld types in the section “Style Sheets for Other Media Types” later in this chapter.

Specifying the Media Type

Next, let’s look at how you can tell the user agent which medium (or media) the styles you are asking it to render should apply to.

Adding a media Attribute to the link Element

Arguably, the simplest method for linking to a style sheet is to use the link element, like so:

<link rel="stylesheet" href="css/mainstylesheet.css" />

This code tells the user agent that the link is to a style sheet and where it can find the link (css/mainstylesheet.css). The user agent will then deal with the link however it sees fit. You can, however, scope the use of the CSS contained in that style sheet with the media attribute:

<link rel="stylesheet" href="css/mainstylesheet.css" media="screen" />

In this example, only devices that will be displaying the content on a large screen will do anything with that style sheet. And where screen is concerned, that pretty much means a PC (Windows, Mac, Linux, etc.) and a web browser (Firefox, IE, and so on).

Adding a media Attribute to the @import Statement

If you are using the @import method for linking to a style sheet (perhaps to throw older, non-standards-friendly browsers such as Netscape 4 off the scent), you could use the following syntax:

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

There is a small problem with this approach, however: IE versions 6 and earlier won’t deal with this syntax (at the time of this writing, IE 7 didn’t understand this construct either), so you’re probably going to have to use the previous method for linking wholesale to a CSS file.

Note: You can place the @import statement in a style block as shown in the example, or you can embed that @import statement in another style sheet that is already linked to the document, but the @import statement must be at the beginning of that style sheet, not after any other CSS selectors.

Adding the Media to Specific Selectors within a Style Sheet

Finally, you can embed some media-specific styles within another style sheet like so:

<style type="text/css">
  body {
    font-size: 62.5%;
  }
  h1 {
    color: red;
  }
  h2 {
    color: blue;
  }
  @media print {
    h1 {
      color: black;
    }
    h2 {
      color: gray;
    }
  }
</style>

Creating a Print Style Sheet

In our experience, the greatest use you’ll have for different media types is with printed output. There are a few quirks to be aware of (and we’ll cover those), but it’s very well supported in general and can be put to great use.

We’ve mentioned the various techniques that you can use to link to a style sheet with different media. Our preference is to do the following:

Note: You should declare the print style sheet last (link to it even after any <style></style> block inside the HTML page). If you declare the print style sheet first, you could undo any values set there in the subsequent generic style sheets if they are not scoped for screen or some other medium.

Translating that English into markup, we get this in the document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple print test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link rel="stylesheet" href="css/basic.css" />
    <link rel="stylesheet" href="css/print.css" media="print"  />
</head>

and in the basic CSS file:

@import url("advanced.css");

What Do You Put in a Print CSS File?

There are not any real hard-and-fast rules about what should or shouldn’t go into a print CSS file. However, let’s take a moment to consider some of the characteristics of the printed format. Keep in mind that in print you can’t do the following:

What you can do with print CSS is almost the reverse of the previous list:

In fact, anything that you can click on or interact with on screen may need some kind of alternative treatment for print. Examples include hiding the element entirely or removing some display attribute that no longer works in the printed format (for example, removing underlines in body text links).

Note: In most browsers, you do not need to be too concerned about dealing with background images that appear on screen; they are usually set not to print by default and, as such, are unlikely to need any special print-only treatment. One exception is Opera, which will print backgrounds out by default (or at least it does in versions 8 and 9 that we tested), but this can easily be unset in the File » TRA Print Options menu. If you have a sufficient number of Opera users, you might want to override background images for given elements, for example, body {background-image:none;}, so that users do not have to specify this for themselves—but it’s not a major consideration that you need to worry about.

One of the first things you should consider with a print layout is resetting any layout mechanisms you’ve used for the screen view. This involves removing floats, absolute positioning, padding, and margins.

Tips for Even Better Printed Pages

Our previous example showed a simple printout that you can achieve by resetting certain CSS properties and redefining others. There is more that you can do to improve matters, though:

Things to Watch Out For

With a little care and attention, you can create web pages that perfectly suit the printed medium. Yet be aware that there are some things you need to take into account.

Checking Your Page Width

If you have defined a width for your page using pixels, you will need to redefine that for print using a real-world measurement such as centimeters, millimeters, or inches. Be sure to allow for the fact that the printer your site visitor is using may not be able to print right up to the edges. If you take a US letter or A4 sized piece of paper, measure its width, then take off a couple of centimeters or a quarter inch from either side, that should give you a printable page width.

Printing Errors with CSS Positioning

If you have reset all the positioning properties as suggested earlier in this chapter, you will probably not run into difficulties. However, be sure to try printing a web page with a lot of content—a page that you would expect to run into several printed pages—to make sure that the entire web page prints. Using floats and absolute position can affect the printout, resulting in only the first page getting printed. If this happens, double-check the CSS for the container of the content that is being “clipped” and ensure that you have set float:none and position:static.

Note: In case you’re wondering “What’s that static value? And why haven’t we heard about it before?” it’s because that’s the browser’s default positioning model. You would not normally need to set this yourself—we only have to do this to get around a known printing problem.

Getting Feedback About Your “Funny Printouts”

Despite all your hard work, someone is bound to ask, “Why does your page not print out properly?” Many users expect that what they see on screen will be replicated in the printout. Remember that you can use print CSS itself to address the issue (e.g., perhaps a block of text that reads “This page has been crafted for perfect printing...” that is hidden on screen but set as display:block for the printed version).

Advanced Print CSS Techniques

Hiding and showing or restyling content dependent on the medium is fairly straightforward stuff once you’ve grasped the basics. In this section, we’ll examine some more advanced features that introduce some extra dynamics into the usually static world of print. This is where browser support can get a little flakier, though, so be sure to treat these as nice-to-haves, rather than as essential features that must be available to all browsers.

Inserting URLS in Printed Pages

The great thing about reading a web page with links is that when you see an underlined phrase you can click on that link and immediately investigate another avenue.

With that page printed out, you have no way of following that link, so you have a couple of choices:

The latter is definitely doable, but it requires some slightly advanced CSS (not supported by IE 7 or earlier) or a JavaScript solution.

Using Generated Content to Write Out the URL

Here is the basic CSS that does the job of writing out links on the page (be sure to add this only to the print CSS file):

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

This code tells the browser to get the value of an attribute (the href attribute, as detailed in the parentheses) and then place that value in a string that begins and ends with parentheses. If you are familiar with JavaScript, it’s equivalent to

" (" + this.getAttribute('href') + ")"

but there is no concatenation symbol such as + or &. In this example HTML:

<h3>
<a href="/book/bookDisplay.html?bID=10079">
Building Flickr Applications with PHP
</a>
</h3>

it would render on the printed version like so:


Building Flickr Applications with PHP
(http://www.apress.com/book/bookDisplay.html?bID=10079)

Tip: You probably wouldn’t want every link on the page to get this treatment, so you may want to scope it by using a contextual selector, for example #bodycontent a:after {content: " (" attr(href) ") ";}.

When looking at a block of content, a long URL directly after the text can make it a little difficult to read, regardless of the benefit offered by having the reference there. Wouldn’t it be great if you could simply create a footnote from each link and just place a number after the link that references the footnote link? Well, you can thank Aaron Gustafson for devising a JavaScript technique that does just that, all ready for you to download and implement.

Selective Printing Using the DOM and CSS

One final advanced technique that you might like to consider is mixing together DOM scripting and CSS to create specific printable areas of a page. An example of how this works is a FAQ page that contains many blocks of content. You might want to print only one section of that page; by using JavaScript you can dynamically toggle display attributes of different sections so that only the part you want printed is shown—but without affecting the screen view.

This is a fairly involved technique, which is covered thoroughly (a chapter in its own right!) in another Apress book, Web Standards Creativity (February 2007), although you can also read about the technique online on my personal blog.

Style Sheets for Other Media Types

As we mentioned at the beginning of this chapter, the support for other media types is very spotty indeed, and what you can do with it is severely limited. We won’t explore all the various CSS property values that you can use with audio style sheets (it’s highly unlikely that such a discussion would be of use to most readers), but we’ll look at a few media types.

The Projection Media Type

Another media type that does have a modicum of support is projection. As far back as version 4, Opera has supported this type, but what does it do? Projection is intended for use with presentation versions of a web page; all browser toolbars and the like are removed, and the information is presented in full screen. A good example is S5, a web-page-based presentation format that CSS guru Eric Meyer devised, and which is used by many web standards advocates throughout the world. In Opera you trigger the Projection mode by choosing View » TRA Full Screen. Firefox and IE will not render the projection content when viewed in full-screen mode, so you have to ask yourself: What benefit can you get from using this?

The Aural Media Type

With the aural CSS properties, you should be able to control the pitch, speed, tone, and other attributes for speech-synthesized versions of the web page to great effect, but support for this is very much lacking. To date, we’ve only seen (or rather heard) one good application of this: a plug-in for Firefox called Firevox, which is definitely worth downloading and checking out to see what should be possible with this technology. You can find out more about the various CSS aural properties and values at the W3C (www.w3.org/TR/REC-CSS2/aural.html), or for a simpler example try the W3Schools introduction to this topic.

The Handheld Media Type

Another example of “great in theory, but almost useless in practice,” the handheld media type is perfect for specifying styles that can be used for a cell-phone-based browser, Blackberry, or similar device. However, the mobile market (phones in particular) are almost a law unto themselves and have devised various strategies for rendering web pages in the struggle to gain a competitive edge. At http://css-discuss.incutio.com/?page=HandheldStylesheets you’ll find a quotation that pretty much sums up the sorry state of handheld support:

Some current phones apply “screen” styles as well as “handheld” styles, others ignore both, and in some cases the phone carrier runs pages through a proxy that strips styles out even if the phone could recognize them, so it’s a crapshoot figuring out what will get applied.

So, all bets are off! It’s good to be aware that the media type exists and what its intended use is, but, seriously, don’t waste effort in trying to design a slick interface for a given handheld device and expect it to honor only your handheld styles and ignore the screen styles—and certainly don’t expect the next handheld to do the same.

The All Media Type

The all media type is pretty much superfluous. If you want a style sheet to be rendered on all devices, you may just as well not set a media type at all and let the device, browser, or user agent work it out for itself.

Summary

The ability to create specific style sheets for different media seems, on the face of it, to be a very powerful tool. However, in practice you are limited in what you can do. It seems a shame to end on a sour note, but we hope the things that you can do with the print medium more than make up for the rest. Now, if only the mobile market could decide on a standard and stick with it, we could do great things with those devices just as we can with the printed medium. Well, we can hope—and a good place to start is with Blue Flavor’s presentation on mobile web design.

Excerpted from “Pro CSS Techniques” by Jeff Croft, Ian Lloyd, and Dan Rubin. Copyright Ian Lloyd 2006. Used with permission of Apress, Inc.

Got something to say?

Share your comments  with other professionals (0 comments)

Related Topics: CSS, DOM

 

Ian Lloyd founded Accessify.com, a web accessibility site, back in 2002 and has been a member of the Web Standards Project since 2003, where he is part of the Accessibility Task Force. He has written or co-authored a number of books on the topic of standards-based web design/development and lives in Swindon, UK, a place best known for its 'Magic Roundabout' and Doctor Who's Billie Piper. (It's not all bad, though.)

Media Temple

via Ad Packs