CSS - @page



CSS 中的 @page at-rule 用於指定網頁列印時列印頁面的樣式。它允許您控制從網頁生成的列印文件的佈局和外觀。使用 @page at-rule,您可以為頁面邊距框、頁面大小、頁首、頁尾等定義不同的規則。

它有助於自定義頁面的尺寸、方向和邊距。您可以使用 CSS 的偽類來定位文件的所有頁面或其子集。

語法

@page = 
   @page <page-selector-list> { <declaration-list> } 

建議不要在 @page at-rule 中使用與視口相關的 <length> 單位,例如 vh、vw、vminvmax

@page at-rule 允許使用者為規則命名。此名稱在宣告中使用 CSS 屬性 page 呼叫。

  • page: 允許選擇器使用使用者定義的 命名頁面

  • <page-body> 包括頁面屬性和頁面邊距屬性

  • <pseudo-selector> 包括以下偽類

    • :first

    • :left

    • :right

邊距 at-rules

@page at-rule 包含 邊距 at-rules。這些邊距 at-rules 負責定位文件的不同部分,從而根據樣式塊中設定的屬性值對列印頁面區域進行樣式設定。

各種 邊距 at-rules 如下所示

  • @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

命名頁面

列印時執行每頁佈局並在宣告中新增分頁符,可以使用 命名頁面 來啟用。這些 命名頁面 可以使用 page 屬性應用。因此,使用者可以建立不同的頁面配置以用於列印佈局。

示例

以下是 @page at-rule 的示例。

<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 元素指定了一個樣式塊。

  • 文件被分成三個部分,每個部分都換頁。

  • 當點選“列印”按鈕時,文件以列印格式開啟,您可以看到每個頁面邊距的變化,這些變化是使用 @page at-rule 設定的,其中大小為橫向,邊距為 15%。

描述符或相關屬性

下表列出了與 @page 相關的所有描述符

描述符/屬性 描述
page 指定命名頁面,即由 @page at-rule 定義的特定型別的頁面。
margin 設定元素四側的邊距區域。
page-orientation 確定頁面的方向。
size 定義用於表示頁面的框的大小和方向。
:first 表示列印文件的第一頁。
:left 表示列印文件的所有左側頁面。
:right 表示列印文件的所有右側頁面。
廣告

© . All rights reserved.