CSS 中的 @page 规则用于指定打印网页时打印页面的样式。它允许您控制从 Web 页面生成的打印文档的布局和外观。使用 @page 规则,您可以为页边距框、页面大小、页眉、页脚等定义不同的规则。
它有助于自定义页面的尺寸、方向和边距。您可以使用 CSS 的伪类来定位文档的所有页面或文档的子集。
语法
@page =
@page <page-selector-list> { <declaration-list> }
建议不要在 @page 规则中使用与视区相关的 <length> 单位,例如 vh、vw、vmin 和 vmax。
@page 规则允许用户为规则指定名称。此名称在 CSS 属性页的声明中调用。
- page:允许选择器使用用户定义的命名页面。
- <page-body> 包括 page-properties 和 page-margin-properties
- <pseudo-selector> 包括以下伪类:
- :first
- :left
- :right
margin 规则
@page 规则 包含 margin 规则。这些 margin 规则负责定位文档的不同部分,进而根据 style 块中设置的属性值设置打印页面区域的样式。
各种margin 规则如下:
- @top-left
- @top-left-corner
- @top-center
- @top-right
- @top-right-corner
- @bottom-left-corner
- @bottom-left
- @bottom-center
- @bottom-right
- @bottom-right-corner
- @left-top
- @left-middle
- @left-bottom
- @right-top
- @right-middle
- @right-bottom
命名页面
可以使用 Named pages (命名页面) 启用打印时执行每页布局并在声明中添加分页符。可以使用 page 属性应用这些命名页面。因此,用户可以创建不同的页面配置以用于打印布局。
例下面是 @page 规则的示例。
<html>
<head>
<style>
@page {
size: landscape;
margin: 15%;
}
section {
page-break-after: always;
break-after: page;
background-color: aquamarine;
width: 500px;
}
@media print {
button {
display: none;
}
}
</style>
</head>
<body>
<article>
<section>
<h2>Header1</h2>
<p>
Section one
</p>
</section>
<section>
<h2>Header2</h2>
<p>
Section two
</p>
</section>
<section>
<h2>Header3</h2>
<p>
Section three
</p>
</section>
</article>
<button style="background-color: green; color: white; font-size: 1em;">Print</button>
<script>
const button = document.querySelector("button");
button.addEventListener("click", () => {
window.print();
});
</script>
</body>
</html>
在上面的示例中:
- 为 div 元素指定了一个 style 块。
- 文档分为三个部分,每个部分都分为一个新页面。
- 单击“打印”按钮时,文档以打印格式打开,您可以看到每页上边距的变化,这是使用 @page 规则设置的,其中大小为横向,边距为 15%。
下表列出了与 @page 相关的所有描述符:
| 描述符 / 属性 | 描述 |
|---|---|
| page | 指定命名页面,这是由 @page 规则定义的特定类型的页面。 |
| margin | 设置元素四边的边距区域。 |
| page-orientation | 确定页面的方向。 |
| size | 定义用于表示页面的框的大小和方向。 |
| :first | 表示打印文档的第一页。 |
| :left | 表示打印文档的所有左侧页面。 |
| :right | 表示打印文档的所有右侧页面 |

