HTML Print Styles
In this page:
<style>
@media print {
selector { property: value; }
}
</style>
The Print Media Query
You can write CSS rules that only run when your webpage is sent to a printer by using the print media query. This allows you to completely customize your page layout specifically for physical paper dimensions.
Example: The Print Media Query
<style>
@media print {
body {
font-size: 12pt;
}
}
</style>
Hiding Interactive Elements
When printing a webpage, interactive elements (like sidebars, navigation menus, and submit buttons) are completely useless on paper and should be hidden using the display: none property.
Example: Hiding Interactive Elements
<style>
@media print {
.no-print {
display: none;
}
}
</style>
<nav class="no-print">Navigation</nav>
Reformatting Colors and Backdrops
Printers do not print bright colors or dark backgrounds well. To save ink and keep your documents readable, your print styles should use high-contrast black text on a clean, white background.
Example: Reformatting Colors and Backdrops
<style>
@media print {
body {
background-color: white;
color: black;
}
}
</style>
Controlling Page Breaks
Printers split content onto physical sheets based on paper length. This can cause headings to print at the very bottom of a page, separated from their paragraphs on the next sheet.
You can use CSS properties (like break-before or break-inside) to control where page breaks occur.
- Applying break-before:
- always; to too many elements can cause the printer to output mostly blank pages.
Example: Controlling Page Breaks
<style>
@media print {
tr {
break-inside: avoid;
}
}
</style>
Displaying Link URLs next to Text
On a physical piece of paper, clickable links are useless since readers cannot click them. To help paper readers find your referenced pages, you can use CSS pseudo-elements to automatically print the actual URL path next to your link text.
Example: Displaying Link URLs next to Text
<style>
@media print {
a::after {
content: " (" attr(href) ")";
}
}
</style>
- Neglecting print tests, leaving messy navigation menus and sidebars to print onto paper.
- Allowing table rows or headers to split awkwardly across page breaks, making data hard to read.
- Failing to print actual URL paths next to your link texts, leaving paper readers unable to find your pages.
- The print media query allows you to define custom layout and design rules specifically for physical paper.
- Use display: none to hide interactive elements like menus and buttons that are useless on paper.
- Enforce high-contrast black-and-white colors to save ink, control page breaks cleanly, and print actual URL paths next to your link text.
Standard print stylesheets and page-break properties are supported natively by all web browsers.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: