How can you make a sticky header and/or footer for @media print only with HTML and CSS? I've tried using position: absolute
and position: fixed
and it doesn't work.
Using position:absolute
and position:fixed
won't work. That would either repeat the header/footer on the first or last page. What you need to do is: Set manually header and/or footer on every page, have content with a fixed height and overflow hidden, and use page-break-*
CSS property to make the browser create a new page on the beginning of the page.
So on the browser it would show all the content
s without any headers and footers, and when printing it would include. If one of the content
doesn't take the whole paper, it would leave some empty space until the footer
, and if it is too big it would be hidden.
<body>
<div class="page">
<div class="header">...</div>
<div class="content">...</div>
<div class="footer">...</div>
</div>
<div class="page">...</div>
</body>
And on CSS:
.page .header, .page .footer {
display: none;
}
@media print {
.page {
page-break-before: always;
}
.page .content {
height: 24cm;
overflow: hidden;
}
.page .header, .page .footer {
display: block;
}
}
Also notice that on @media print
measurements should be done in physical units, so you should use cm
or in
instead of px
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With