I wanted to add a header and footer on each page of the printed version of my website, and I used the following method
@media print {
/* the parent container */
table.report-container {
page-break-after:always;
}
/* the parent container */
thead.report-header {
display:table-header-group;
}
/* the footer container */
tfoot.report-footer {
display:table-footer-group;
}
}
The HTML code is as following:
<table >
<!-- the header -->
<thead >
<tr>
<th>
<h1>Header</h1>
</th>
</tr>
</thead>
<tbody >
<tr>
<td>
<!-- body -->
</td>
</tr>
</tbody>
<!-- the footer -->
<tfoot >
<tr>
<td>
<h1>Footer</h1>
</td>
</tr>
</tfoot>
</table>
the problem with this method, that in the last page the footer will not be displayed at the end of the page, unless the page body has filled the intire page. like the following:
All I need is to find a way to enforce the footer to be always displayed at the end of the page.
CodePudding user response:
Try this CSS in print as you used.
.report-footer{
position: fixed;
bottom: 0;
background:red;
display: block;
width:100%;
}
<table >
<thead >
<tr>
<th>
<h1>Header</h1>
</th>
</tr>
</thead>
<tbody >
<tr>
<td>
<!-- body -->
</td>
</tr>
</tbody>
<tfoot >
<tr>
<td>
<h1>Footer</h1>
</td>
</tr>
</tfoot>
</table>
CodePudding user response:
You can make use of %
as it is always inherited from parent
element.
If you set parent's
height to 100%
and footer's min-height
to 100%
, so it will work.
Here is a minimal reproducible example:
Html code:
<header>
this is header part
</header>
<section>
this is content part
</section>
<footer>
this is footer part
</footer>
css code
html,
body {
height: 100%;
}
header {
border: 2px solid blue;
text-align: center;
}
section {
border: 2px solid red;
min-height: 100%;
text-align: center;
}
footer {
border: 2px solid green;
text-align: center;
}
Note:
Here section's direct parent is body.
CodePudding user response:
It is enough to determine the dimensions of the <table>
and it parents (up to <body>
and/or <html>
) to do it easily and with no additional changes:
html,
body,
table {
height: 100%;
}
You can use this code in the @media print { ... }
.
Code snippet:
html,
body,
table {
height: 100%;
}
/* the parent container */
table.report-container {
page-break-after: always;
}
/* the parent container */
thead.report-header {
display: table-header-group;
}
/* the footer container */
tfoot.report-footer {
display: table-footer-group;
}
<body style="min-height: 5in;">
<table >
<!-- the header -->
<thead >
<tr>
<th>
<h1>Header</h1>
</th>
</tr>
</thead>
<tbody >
<tr>
<td>
<!-- body -->
</td>
</tr>
</tbody>
<!-- the footer -->
<tfoot >
<tr>
<td>
<h1>Footer</h1>
</td>
</tr>
</tfoot>
</table>
</body>