Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

CSS @page rule: จัดรูปแบบหน้าพิมพ์


กฎ @page

กฎ @page ใช้กำหนดขนาด ทิศทาง ขอบเขต ของกล่องหน้า (page box) สำหรับสื่อพิมพ์ (Print Media) ใช้ร่วมกับ @media print

คุณสมบัติหลักใน @page

คุณสมบัติหน้าที่
sizeขนาดและทิศทางหน้ากระดาษ
marginขอบหน้ากระดาษ
margin-top/bottom/left/rightขอบแต่ละด้าน
marksเครื่องหมายตัด (crop marks, cross marks)
bleedพื้นที่ล้น (bleed area)

ตัวอย่าง: กำหนดขนาดและขอบ

<style>
  @page {
    size: 8.5in 11in;  /* Letter size */
    margin: 2cm;
  }
</style>

ค่า size ที่ใช้ได้

  • auto - ตามกระดาษเป้าหมาย (default)
  • landscape - แนวนอน
  • portrait - แนวตั้ง
  • <length> <length> - กำหนดความกว้าง ความสูง (cm, mm, in, px)

Pseudo-classes ใน @page

/ หน้าแรก /
@page :first {
  margin-top: 3cm;
  @top-center { content: "Cover Page"; }
}

/ หน้าคู่ (ซ้าย) /
@page :left {
  margin-right: 3cm;
  @bottom-left { content: counter(page); }
}

/ หน้าคี่ (ขวา) /
@page :right {
  margin-left: 3cm;
  @bottom-right { content: counter(page); }
}

/ หน้าว่าง /
@page :blank {
  @top-center { content: "This page intentionally left blank"; }
}

Page Margin Boxes

สามารถวางเนื้อหาในพื้นที่ขอบได้ 16 ตำแหน่ง:

@page {
  @top-left { content: "Book Title"; }
  @top-center { content: "Chapter " counter(chapter); }
  @top-right { content: counter(page); }
  @bottom-center { content: "© 2024 Company"; }
}

ตัวอย่างสมบูรณ์สำหรับหนังสือ

@media print {
  @page {
    size: A4;
    margin: 2.5cm;
    marks: crop cross;
    bleed: 5mm;
  }
  
  @page :first {
    margin-top: 5cm;
  }
  
  @page :left {
    @bottom-left { content: counter(page); }
    @bottom-center { content: string(chapter-title); }
  }
  
  @page :right {
    @bottom-right { content: counter(page); }
    @bottom-center { content: string(book-title); }
  }
  
  h1 { string-set: chapter-title content(); }
  h1 { string-set: book-title "My Book"; }
}