I’m putting together an HTML document that needs to be A4 sized and needs to be very strict about the positioning and styling of its items, so I’m using Paged.js to set up pages while also maintaining my own stylesheet. All elements of this document must be consistent in the browser’s (Chrome) print mode, as that is what I made this page for.
Here’s the HTML structure:
<body>
<div class="header"></div>
<div class="content">
<div class="main"></div>
<div class="footer"></div>
</div>
</body>
And here’s the CSS, just the part that matters:
@page {
size: A4;
margin: 0.4in;
}
body {
width: 21cm;
margin: auto;
font-family: var(--font);
font-size: 13px;
box-sizing: border-box;
}
.header {
position: fixed;
top: 0;
width: 100%;
z-index: 10;
margin: 0.4in
}
.content {
margin-top: 115px !important; // default space for the header, so it doesn't overlap the content
}
.main {
margin-bottom: 20px; // some space between main and the footer
}
.footer {
display: block;
position: absolute;
bottom: 0;
height: 195px; // the footer's actual height
width: 100%;
page-break-inside: avoid;
}
The footer has a rule that it must always be positioned at the end of the page it’s on, and since it’s the last element in the document, it will always be on the last page generated by Paged.js.
The content of main is the only content in the entire document that can vary in size, while the rest is fixed. In other words, main can take up less than the first page, leaving space for the footer, or it can take up more than one page, creating a new page, causing the footer to move the bottom os this new page.
The problem is when main’s size is not enough for it to create a new page, and since the footer has an absolute position, main ends up overlapping the footer.
I’ve tried to solve this in several ways, but nothing has worked so far. And in some attempts, like using margin-top auto on the footer and making the content as flex, the footer was never on the same page as the main’s page, even if there was space.
I’ve already tried to do something similar to the header I set up, but the header is an element that needs to be at the top of all pages, so setting a default margin value for it is a good option. The footer, on the other hand, is different, and if I set a default value for the footer, there will be situations where the footer won’t be on a certain page (because main got too big and took up several pages), and there will be unnecessary space.
And changing the footer’s position to relative just makes it disappear on print.
Guilherme Henrique is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.