如何实现A4打印页面固定页眉页脚且主体内容不重叠
解决固定页眉页脚与主体内容遮挡及A4打印适配问题
核心思路
使用position: fixed固定页眉页脚后,元素会脱离正常文档流,因此需要给主体内容设置上下外边距,值匹配页眉和页脚的高度(可额外加少量间距),避免内容被遮挡。同时通过打印媒体查询(@media print)优化A4打印布局,确保每一页都能正确显示页眉页脚,内容排版整齐。
完整代码实现
HTML(保留原有结构,清理冗余标签)
<header> <div class="container"> <div class="right"> <h2>مـختبر</h2> </div> <div class="left"> <img src="../imgs/logo.png" alt=""> </div> </div> </header> <main> <div class="container"> <table> <tr> <th>Test</th> <th>Result</th> </tr> <?php for ($i=0 ;$i<109 ; $i++){?> <tr> <td> <select name="" id=""> <option value="">choose</option> </select> </td> <td> <input type="text" name="" id=""> </td> </tr> <?php } ?> </table> </div> </main> <center> <button class="print hideprint" title='print' onclick="printPage()"> <img src='../imgs/print.png' style='height:auto;width:60px'> </button> </center> <footer id='footer'> <div class="container"> <div class="loc">العنوان</div> </div> </footer> <script> function printPage() { window.print(); window.location.reload(); } </script>
CSS 样式
/* 全局基础样式 */ * { margin: 0; padding: 0; box-sizing: border-box; } /* 页眉固定样式 */ header { position: fixed; top: 0; left: 0; width: 100%; height: 80px; /* 根据实际页眉高度调整 */ background: #fff; border-bottom: 1px solid #ccc; padding: 10px 20px; } /* 页脚固定样式 */ footer { position: fixed; bottom: 0; left: 0; width: 100%; height: 60px; /* 根据实际页脚高度调整 */ background: #fff; border-top: 1px solid #ccc; padding: 10px 20px; } /* 主体内容:避开页眉页脚 */ main { margin-top: 100px; /* 页眉高度+额外间距,避免紧贴 */ margin-bottom: 80px; /* 页脚高度+额外间距 */ padding: 0 20px; } /* 打印专用样式 */ @media print { /* 隐藏打印按钮 */ .print { display: none; } /* 设置A4页面尺寸与边距 */ @page { size: A4; margin: 10mm; /* 预留边距,防止页眉页脚超出打印区域 */ } /* 打印时保持页眉页脚固定 */ header { position: fixed; top: 0; } footer { position: fixed; bottom: 0; } /* 打印时主体内容适配边距 */ main { margin-top: 80px; /* 与页眉高度一致 */ margin-bottom: 60px; /* 与页脚高度一致 */ page-break-inside: avoid; /* 避免表格内容在页中间断裂(可选) */ } /* 表格打印适配 */ table { width: 100%; border-collapse: collapse; } table th, table td { border: 1px solid #ccc; padding: 8px; font-size: 12px; } }
关键说明
- 外边距匹配:
main的margin-top和margin-bottom需大于等于页眉、页脚的高度,确保内容不会被遮挡。 - 打印布局优化:
@page设置A4尺寸和页面边距,防止页眉页脚超出打印范围;隐藏打印按钮避免干扰打印内容。 - 表格可读性:
page-break-inside: avoid可减少表格行在页面中间被截断的情况,提升打印效果。
内容的提问来源于stack exchange,提问作者user24207902
相关产品推荐
相关产品推荐

