HTML & CSS: Create header and footer on the top and bottom of every printed page

An easy way to print header and footer on every page using html and css only.

HTML & CSS: Create header and footer on the top and bottom of every printed page

Recently, I had to update the print layout for the customer and add header and footer information to documents they print through a web app we custom built for them. The problem we faced and solved is that header and footer don’t always act as expected on every page which took some creativity into resolving the issue.

Method #1 - CSS position:fixed

Our first solution was to set position:fixed property of header and footer elements. Our code looked like this:

<div class=”header”>Header</div>

<div class=”content”>Content…</div>

<div class=”footer”>Footer</div>

 

CSS:

.header {
position: fixed;

top: 0;
}
.footer {
position: fixed;
bottom: 0;
}

 

CSS Html header footer - one page simple

 

And this looked fine if content was less than 1 page long. When you try to print more than 1 page overlap happens:

CSS & HTML Header and footer - overlap issue CSS & HTML Header and footer - overlap

 

Then we tried a new method – using tables.

Method #2 – Using html tables

When printing a html table, thead and tfoot elements appear in the top and bottom of every page by default. Only exception that table footer on the last page is printed after the content and not on the bottom.

CSS & HTML Header and footer - using table structure overlap issue CSS & HTML Header and footer - using table structure overlap issue

 

FINAL SOLUTION

Final solution to printing header and footer on the top and bottom of every page using css and html was to combine these two solutions.

Content will be shown in the table. Header will be printed inside thead element.

To print the footer we used footer div and table footer. This is the code:

<table>
<thead><th><td><div class=“empty-header“></div></td></th></thead>
<tbody><tr><td><div class=“content“></div></td></tr></tbody>
<tfoot><div class=”empty-footer”>Footer</div></tfoot>
</table>
<div class=”header”>Header</div>
<div class=”footer”>Footer</div>

CSS:

.empty-header, .empty-footer {
height:100px
}
.header, .footer {
position: fixed;
height:100px;
top: 0;
}
.footer {
               bottom:0
}

Final result:

CSS & HTML Header and footer - using table structure and css - final solution CSS & HTML Header and footer - using table structure and css - final solution


Comment & share

Kategorije: solutions

Ključne riječi: css, html, header, footer, multiple pages, issue