How to create a printable HTML page with custom A4 layout

Creating printable HTML pages can be tricky, even for experienced frontend developers. I remember tackling this challenge a few years ago, and I had to dig deep into research and community solutions like StackOverflow. To save you some time and effort, I’ve put together this guide that walks through the process step-by-step.


Step 1: Set up the basic structure

Start by setting up a div container with the class print-container. Inside it, include another div with the class page-A4. This structure will hold your content. Below, I’ve added an article element as an example.

<div class="print-container page-A4">
    <section class="page-content">
        <article>Ciao! I'm an A4 document.</article>
    </section>
    <section class="page-content">
        <article>Ciao! I'm an A4 document.</article>
    </section>
</div>

Step 2: Basic styling

Apply base styles to maintain layout integrity:

body {
    margin: 0;
}
.print-container {
    margin: 0;
}
.page-content {
    margin: 0;
    overflow: hidden;
    position: relative;
    box-sizing: border-box;
    page-break-after: always;
}

Step 3: Screen display enhancements

To make the page look more like a printed sheet when viewed on a screen, add these styles:

@media screen {
    body {
        background: #f4f4f4;
    }
    .page-content {
        background: white;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        margin: 10mm auto;
    }
}

Step 4: Set page size to A4

Define the dimensions of the A4 page using millimeters:

.page-a4 .page-content {
    width: 210mm;
    height: 297mm;
}
.page-padding {
    padding: 10mm;
}

Add the page-padding class for easy margin adjustments:

<div class="print-container page-a4">
    <section class="page-content page-padding">
        <article>Ciao! I'm an A4 document.</article>
    </section>
    <section class="page-content page-padding">
        <article>Ciao! I'm an A4 document.</article>
    </section>
</div>

Step 5: Configure print setting

Lastly, ensure your CSS sets the correct page size for printing:

@page {
    size: A4;
    margin: 0;
}
@media print {
    .print-container.page-a4 {
        width: 210mm;
    }
}

By following these steps, you’ll achieve a properly formatted A4 printable layout for your web content.

Let me know in the comments if you try it or have any questions!