Article Image
News Link • How To

Using CSS to Format Documents for Printing

• https://www.makeuseof.com, BY BOBBY JACK

If you've ever printed off ticket reservations or directions to a hotel from the web, you've probably been less than impressed with the results. You may, therefore, be unaware that printed documents can be styled in much the same way that they can on-screen, using Cascading Style Sheets (CSS).

Separation of Concerns

A key benefit of CSS is the separation of content from presentation. In the simplest terms, this means instead of very old-fashioned stylistic markup such as:

Heading

We use semantic markup:

Heading

Not only is this much cleaner, it also means our presentation is separated from our content. Browsers render h1 elements as large, bold text by default, but we can change that style at any time with a stylesheet:

h1 { font-weight: normal; }

By gathering those style declarations in a separate file, and referencing that file from our HTML document, we can make even better use of separation. The style sheet can be reused, and we can change that single file at any time to update the formatting in every document that uses it.

Including a Print Style Sheet

In a similar manner to including a screen style sheet, we can specify a style sheet for print. A screen style sheet is typically included like so:

However, an additional attribute, media, allows targeting based on the context in which the document is rendered. By default, the previous element is equivalent to:

This means the stylesheet will be applied for any medium the document is rendered in. However, the media attribute can also take values of print and screen:

In this example, the print.css stylesheet will only be used when the document is printed out. This is a very useful mechanism. We can gather all common styling (perhaps font family or line spacing) in a stylesheet that applies to all media, and media-specific formatting in individual stylesheets. Again, this is another use of separation of concerns.


thelibertyadvisor.com/declare