css@page 如何设置页眉页脚

2025-10-31 09:44:46

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

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

语法:

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

取值:

<label>:

页面标识符

<pseudo-class>:

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

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

css@page 如何设置页眉页脚

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

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

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

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

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

@page :first {

 

  margin-left: 50%;

 

  margin-top: 50%;

 

}

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

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

这是分页标记的样式

.geovindu{

 

  page-break-after: always;

 

}

7、这是页眉的样式

.pageheader {

margin-top: 10px;

font-size:12pt;

}

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

8、这是页眉的样式

.pagefooter{

margin-top: 10px;

font-size:10pt;

}

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

9、接下来在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>

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

10、最后贴上完整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: 50px; margin-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>

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢