CSS 打印



CSS 打印涉及使用特定的 CSS 规则和属性来控制网页在打印时的格式。通常,对于任何可打印的网页版本,样式都将使用浅色。因为黑色、红色等深色会消耗打印机更多的墨水。在本教程中,我们将学习如何使用 CSS 设计一个打印友好的网页。

目录

打印友好页面的样式

以下是可用于创建打印友好页面的关键样式

  • 简化布局: 通过将display 设置为 none,移除不必要的元素,例如侧边栏、导航菜单、广告部分和交互式内容。
  • 移除背景颜色: 建议移除背景颜色(或设置浅色)并将文本颜色设置为黑色,以节省墨水。
  • 调整字体大小和样式: 使用易于阅读的字体大小和样式,通常是更大、更清晰的字体,例如衬线字体。
  • 显示链接的 URL: 打印包含超链接的页面时,不会显示该链接的确切 URL。因此,您需要在打印版本中用确切的链接替换它。
  • 管理分页符: 确保控制内容在页面间的断开位置,避免将重要的部分或标题拆分到不同的页面。

我们可以通过多种方式为页面的打印版本设置样式。我们可以为打印版本显式声明一个外部样式表,或者可以在内部样式表中使用媒体查询。让我们来看看。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

使用打印样式表

您可以为打印需求显式地创建一个外部样式表,并将其链接到您的代码。您只需要将media 属性的值设置为链接标签的“print”。将以下标签添加到 HTML 文档的 head 部分。

<link href="/path/to/print.css" media="print" rel="stylesheet" />

print.css 将如下所示

body{ background-color: white; color: black; } .navbar{ display: none; }

使用媒体查询和 @page

CSS 媒体查询 可用于在内部样式表中本身设置打印版本的样式。

@media print { body{ background-color: white; color: black; } .navbar{ display: none; } }

CSS @page 规则用于控制打印内容的大小、方向和边距等方面。这对于为所有打印页面设置一致的页面大小和边距以及创建具有特定页面布局的小册子或文档很有用。

@page { size: A4 portrait; /* A4 size, portrait orientation */ margin: 2cm; /* 2cm margins on all sides */ } /* First page has different styling */ @page :first { margin: 5cm; }

让我们来看这两个的例子。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> body{ background-color: black; color: white; padding: 10px; } @media print { body { background-color: white; color: black; padding: 10px; } } @page { size: A4 portrait; margin: 2cm; } button { background-color: aqua; padding: 5px; } </style> </head> <body> <h3> Tutorialspoint </h3> <p>CSS Media Type - Print</p> <p> Background is white for printable version of this page. Check out... </p> <button onclick="printPage()">Print Page</button> <script> function printPage() { window.print(); } </script> </body> </html>

检测打印请求

浏览器会触发“beforeprint”和“afterprint”事件来识别何时要进行打印或打印刚刚完成。您可以使用这些事件来修改打印过程中的用户界面,例如在打印时显示或隐藏特定元素,或者甚至在打印后更改样式。

<script> window.addEventListener("afterprint", () => self.close); </script>

上述声明将在打印其内容后自动关闭当前窗口。让我们来看一个例子。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> button{ background-color: green; color: white; font-size: 1em; } @media screen { h2 { font-size: large; font-family: sans-serif; color: blue; font-style: normal; } } @media print { h2 { font-family: cursive; font-style: italic; color: red; } } @media print { button {display: none;} } </style> </head> <body> <article> <section> <h2>Header1</h2> <p> Section one </p> </section> </article> <button >Print</button> <script> const button = document.querySelector("button"); button.addEventListener("click", () => { window.print(); }); window.addEventListener("afterprint", () => self.close); </script> </body> </html>
广告