打印时如何设置带图片的页眉高度并为内容预留对应顶部间距
问题原因
使用position: fixed定位的元素会脱离普通文档流,浏览器渲染打印内容时不会自动为这类元素预留排版空间,因此正文内容会直接从页面顶部开始渲染,和页眉重叠。
完整解决配置
CSS 代码
@media print { /* 核心配置:设置打印页面的上下边距,数值和页眉、页脚高度一致,强制正文限制在中间区域 */ @page { margin: {header-height} 0 {footer-height} 0; } .divHeader { position: fixed; top: 0; left: 0; width: 100%; height: {header-height}; overflow: hidden; /* 避免图片超出页眉容器 */ } .divFooter { position: fixed; bottom: 0; left: 0; width: 100%; height: {footer-height}; overflow: hidden; /* 避免图片超出页脚容器 */ } /* 兼容兜底:如果部分浏览器对@page规则支持不好,可以额外给body加内边距 */ body { padding-top: {header-height}; padding-bottom: {footer-height}; } }
HTML 代码
<!-- 页眉区域 --> <div class="divHeader"> <img src="你的页眉图片地址" width="100%" alt="页眉"> </div> <!-- 页脚区域 --> <div class="divFooter"> <img src="你的页脚图片地址" width="100%" alt="页脚"> </div> <!-- 待打印的正文内容 --> <div class="print-content"> 所有需要打印的正文内容放在此处 </div>
注意事项
- 替换代码中的
{header-height}、{footer-height}为你实际设置的高度值,例如120px - 页眉、页脚内的图片建议额外设置
max-height: 100%,避免图片高度超出容器导致溢出 - 不同浏览器打印兼容性存在差异,测试时优先使用Chrome浏览器的打印预览验证效果
内容的提问来源于stack exchange,提问作者Sagar Agarwal
相关产品推荐
相关产品推荐

