html怎么添加页眉页脚

html-css0647

html怎么添加页眉页脚,第1张

首先我们来介绍一下@page的相关用法:

@page用于设置页面容器的版式,方向,边空等。

语法:

@page <label><pseudo-classes>{ sRules }

取值:

<label>:

页面标识符

<pseudo-class>:

打印伪类:first, :left, :right

在Firefox,Safari,Internet Explorer,Google Chrome,Opera等浏览器中,默认的页眉是网页title,页脚是第几页/共几页. 只有Microsoft Edge没有默认的页眉,页脚,为了样式统一,我们可以在打印时关闭浏览器自带页眉页脚,统一使用CSS定义的页眉页脚

请点击输入图片描述

接下来,我们在网页中定义专用于打印的CSS样式,在style标签中使用media="print"进行定义,如下

<style type="text/css" media="print">

接下来为每一页设置页边距

@page {margin-left: 50pxmargin-top: 100px}

如果有封面,可以用以下样式单独定义

@page :first {

margin-left: 50%

margin-top: 50%

}

具体样式可根据自己需要写入样式内

接下来再定义几个样式用于分页及页眉页脚

这是分页标记的样式

.geovindu{

page-break-after: always

}

这是页眉的样式

.pageheader {

margin-top: 10px

font-size:12pt

}

具体样式可根据自己需要写入样式内

这是页眉的样式

.pagefooter{

margin-top: 10px

font-size:10pt

}

具体样式可根据自己需要写入样式内

接下来在body标签内输入相关html标签并应用我们的样式

<body>

<script type="text/javascript">

document.querySelector("button").onclick = function () {

window.print()

}

</script>

<div id="geovindu" class="geovindu">

<div class="pageheader">页眉:打印测试</div>

<div class="conent">

封面内容

</div>

<div class="pagefooter">页脚:第1页/共2页</div>

</div>

<div id="geovindu" class="geovindu">

<div class="pageheader">页眉:打印测试</div>

<div class="conent">

第二页内容

</div>

<div class="pagefooter">页脚:第2页/共2页</div>

</div>

<button>打印按钮</button>

</body>

以上仅做为参考,可以根据自己的需要灵活使用

最后贴上完整html,大家可以复制到文本编辑中保存网页来测试

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>打印测试页</title>

<style type="text/css" media="screen">

.pageheader ,.pagefooter {display:none}

</style>

<style type="text/css" media="print">

/*每一页 如果没有另外自定义的话 */

@page {margin-left: 50pxmargin-top: 100px}

/*第一页*/

@page :first {

margin-left: 50%

margin-top: 50%

}

/*分页标记*/

.geovindu{

page-break-after: always

}

.pageheader {

margin-top: 10px

font-size:12pt

}

.pagefooter{

margin-top: 10px

font-size:10pt

}

</style>

</head>

<body>

<script type="text/javascript">

document.querySelector("button").onclick = function () {

window.print()

}

</script>

<div id="geovindu" class="geovindu">

<div class="pageheader">页眉:打印测试</div>

<div class="conent">

封面内容

</div>

<div class="pagefooter">页脚:第1页/共2页</div>

</div>

<div id="geovindu" class="geovindu">

<div class="pageheader">页眉:打印测试</div>

<div class="conent">

第二页内容

</div>

<div class="pagefooter">页脚:第2页/共2页</div>

</div>

<button>打印按钮</button>

</body>

</html>

参考: The Ultimate Print HTML Template with Header &Footer | by Idan Cohen | Medium

使用 table 中的 thead 会在每页打印其中的内容, 而不需要打印页眉页脚的页面(头2页, 3页等), 继续使用 div static 布局

对 tr 使用 break-inside-avoid, break-after-auto

参考: How to Handle Page Breaks when Printing a Large HTML Table