CSS Print Styles for HTML to PDF
How to write CSS print styles for perfect HTML to PDF conversion — page breaks, margins, and media queries.
Published:
Tags: CSS print styles PDF, HTML print media query, @media print CSS
CSS Print Styles for HTML to PDF The CSS Paged Media Module Level 3 W3C specification defines rules, page break properties, and margin handling for print. The CSS Media Queries Level 4 spec defines behavior. MDN's print media guide is the practical reference. Writing CSS print styles controls how your HTML document looks when converted to PDF — page margins, page breaks, hidden navigation, and print-friendly colors. A well-written print stylesheet is the difference between a professional PDF and a broken layout with navigation menus embedded in the page. --- What is @media print Media Query? All print styles go inside rules. These styles only apply when the page is printed or saved as PDF; they have no effect on screen display. Units in print CSS: use (points), , or for print — not . One…
Frequently Asked Questions
How do I write CSS for printing?
Use @media print rules in your stylesheet. Inside the media query, hide navigation and non-content elements (display: none), set print-friendly font sizes and colors, define page margins with @page, and add page-break-* properties to control where pages split.
What is @media print?
@media print is a CSS media query that applies styles only when the page is being printed or saved as PDF. Use it to write a separate print-optimized layout: hide screen-only UI, adjust fonts and colors, set margins, and control page breaks.
How do I add page breaks in CSS?
Use page-break-before, page-break-after, and page-break-inside properties. The modern equivalents are break-before, break-after, and break-inside. Use break-after: page on elements that should always start a new page, and break-inside: avoid to prevent elements from splitting across pages.
How do I handle page margins for printing?
Use the @page rule in CSS: @page { margin: 2.5cm; } for uniform margins, or @page { margin: 2.5cm 2cm; } for top/bottom vs left/right. For books, use @page :left and @page :right to set different margins for odd and even pages.
How do I force images to print with backgrounds?
Set -webkit-print-color-adjust: exact; print-color-adjust: exact; on elements with background images or background colors. Without this, most browsers suppress backgrounds by default when printing to save ink.
All articles · theproductguy.in