CSS @page
在CSS中,@page
规则用于定义打印文档时的页面样式。通过@page
规则,我们可以控制打印页面的大小、边距、页眉、页脚等样式。
基本语法
@page
规则的基本语法如下:
@page {
/* 页面样式 */
}
在@page
规则中,我们可以设置以下属性:
size
:设置页面的大小,可以是固定值(如A4、Letter)或自定义值(如宽度和高度)。margin
:设置页面的边距,可以是固定值(如1cm)或自定义值(如上、右、下、左边距)。@top-left
、@top-center
、@top-right
:设置页眉内容及样式。@bottom-left
、@bottom-center
、@bottom-right
:设置页脚内容及样式。
接下来,我们将通过示例代码来演示如何使用@page
规则。
示例代码
设置页面大小和边距
@page {
size: A4;
margin: 2cm;
}
在上面的示例中,我们设置页面大小为A4,边距为2cm。
设置页眉和页脚
@page {
@top-center {
content: "Header";
}
@bottom-center {
content: "Footer";
}
}
在上面的示例中,我们设置了页眉为”Header”,页脚为”Footer”。
设置自定义页面大小和边距
@page {
size: 210mm 297mm; /* 自定义页面大小 */
margin: 1in 2in 1in 2in; /* 自定义边距 */
}
在上面的示例中,我们设置了自定义页面大小为210mm x 297mm,自定义边距为1英寸的上、2英寸的右、1英寸的下、2英寸的左。
设置不同页眉和页脚
@page {
@top-left {
content: "Left Header";
}
@top-right {
content: "Right Header";
}
@bottom-left {
content: "Left Footer";
}
@bottom-right {
content: "Right Footer";
}
}
在上面的示例中,我们设置了左上角页眉为”Left Header”,右上角页眉为”Right Header”,左下角页脚为”Left Footer”,右下角页脚为”Right Footer”。
设置页面背景颜色
@page {
size: A4;
margin: 2cm;
background-color: lightgray;
}
在上面的示例中,我们设置了页面的背景颜色为浅灰色。
设置页面边框
@page {
size: A4;
margin: 2cm;
border: 1px solid black;
}
在上面的示例中,我们设置了页面的边框为1像素的黑色实线。
设置页面边框和边距
@page {
size: A4;
margin: 2cm;
border: 1px solid black;
padding: 1cm;
}
在上面的示例中,我们设置了页面的边框为1像素的黑色实线,内边距为1厘米。
设置页面旋转
@page {
size: A4 landscape;
margin: 2cm;
}
在上面的示例中,我们设置了页面为横向打印(landscape)。
设置页面多列
@page {
size: A4;
margin: 2cm;
columns: 2;
}
在上面的示例中,我们设置了页面为两列显示。
设置页面分页符
@page {
size: A4;
margin: 2cm;
orphans: 2;
widows: 2;
}
在上面的示例中,我们设置了页面的孤行(orphans)和孤列(widows)为2。
总结
通过@page
规则,我们可以在打印文档时控制页面的样式,包括页面大小、边距、页眉、页脚等。在实际应用中,我们可以根据需要定制不同的打印样式,以提高打印文档的可读性和美观性。