CSS provides the @media print
selector to customize styles for printing. This note documents my practices on using @media_print
to promote paper reading experience of web pages.
Rule 1: Hide UI components
Buttons, forms, navigation bars and other UI components can’t function on papers. And when a reader wants a PDF copy or a printed copy, he or she usually wants only the content of the article. Thus UI components should be hidden.
For example, if a page has a comment area wrapped in a div
with the class comments
, the following CSS should be used.
@media print {
.comments {
display: none;
}
}
Rule 2: Print URLs of Links
Hyper links can’t function on papers. URLs of links should be printed. It can be implemented by a :after
CSS selector. The following CSS snippet is a minimal example.
@media print {
a:after {
content: ' (' attr(href) ')'
}
}
If the page has anchor links, they should be exceptions. Combining a :not()
pseudo-class with an attribute selector filters out anchor links.
@media print {
a:not([href^=\#]):after {
content: ' (' attr(href) ')';
}
}
Mixing text with URLs leads to a terrible reading experience. Selecting a different font for URLs would reduce the chaos. As a URL is used to be typed in a computer, it’s reasonable to take a font that is usually for code.
@media print {
a:not([href^=\#]):after {
content: ' (' attr(href) ')';
font-family: 'Courier New', monospace;
}
}
Rule 3: Turn Scrolling to Wrapping
Code blocks and other formatted texts would better not wrap on screen. We make the container scrollable. However, scrolling doesn’t function on papers. If a page is expected to be printed, it should turn scrolling to wrapping while it’s printed.
@media print {
pre {
white-space: pre-wrap;
}
}
More
There are more things can be done to make pages more friendly to paper reading. While printing, the beginning of a paragraph can be indented; The font may change to a serif one; And so on.