📚 Knowledge Garden

Search

Search IconIcon to open search

Web Page Print Styles

Last updated Aug 13, 2023

When you print a HTML page from the browser, either to a paper printer or to PDF there can be formatting issues. Here I present a few CSS styles that can be used to better present details on the page.

# TL;DR

ISO A4 sized pages, with manual page breaks and avoidance of split elements.

1
2
3
@page { margin: 2rem; size: 21cm 29.7cm; }
hr { page-break-after: always; visibility: hidden; }
html body * { page-break-inside: avoid; }

# Setting the Paper Size

To set the page size and margin, use the @page selector.

1
2
3
4
@page {  
    margin: 2rem;  
    size: 21cm 29.7cm;  
}

The size rule accepts mm (millimetres), cm (centimetres), or in (inches). For standard paper sizes refer to ISO Paper Sizes.

# Forcing Page Breaks

To force a page break, choose an HTML element that seems natural for a page break, generally I use <hr> elements for this purpose.

1
2
3
4
hr {  
    page-break-after: always;  
    visibility: hidden;  
}

Optionally you can hide the element as I have, if it will disrupt the presentation of the document.

# Avoid Splitting Elements

To avoid splitting elements like <p> <code> and <pre> blocks, use the page-break-inside rule. You can apply this to all elements on a page and a best attempt will be made to avoid splitting elements over two pages.

1
2
3
html body * {  
    page-break-inside: avoid;  
}