๐Ÿ–จ๏ธ Chapter 89: HTML & CSS for Print & Paged Media

The CSS @page Rule & Margins

Mastering page box geometry, international paper sizes, custom margin units, orientation switching, and page pseudo-classes.

LEARNING OBJECTIVES โŒต
  • Define physical sheet dimensions and orientations using the @page size property.
  • Configure precise physical margin boxes using millimeters (mm), inches (in), and typographical points (pt).
  • Target specific pages dynamically using pseudo-classes: @page :first, @page :left, and @page :right.
  • Apply named pages (page: landscape-report;) to switch individual sections between portrait and landscape orientations.
๐ŸŽฌ INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
๐ŸŒ
1. Input
Directives & Tags
โš™๏ธ
2. Parse
Tokenizer & AST
๐ŸŒณ
3. Layout
Box Model & Flow
๐ŸŽจ
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

๐Ÿ“– The Mental Model & Story (Intuitive Foundation)

Imagine a master bookbinder crafting a collector's hardcover edition of an encyclopedia. The bookbinder does not treat every sheet of paper identically:

  • The Cover Page has zero margin on the outer edges for full bleed artwork and no header text.
  • The Left Pages (Verso) have extra margin on their right side (the spine gutter) so words don't get sucked into the binding seam when the book is opened.
  • The Right Pages (Recto) have extra margin on their left side for that same gutter.
  • A wide 16-column spreadsheet in Chapter 4 needs the binder to physically rotate the sheet 90 degrees into Landscape orientation without rotating the rest of the book.

In the CSS Paged Media Module, the @page rule is your digital bookbinder. It operates above the <html> and <body> elements, controlling the physical boundaries of the paper itself.

+-----------------------------------------------------------------------------------+
|                                 THE CSS PAGE BOX                                  |
|                                                                                   |
|  +-----------------------------------------------------------------------------+  |
|  |                           @top-center margin box                            |  |
|  +-----------------------------------------------------------------------------+  |
|  |  @top-left  |                                               |  @top-right   |  |
|  |-------------+-----------------------------------------------+---------------|  |
|  |             |                                               |               |  |
|  |  Left       |                 PAGE AREA                     |  Right        |  |
|  |  Margin     |           (HTML/Body Content)                 |  Margin       |  |
|  |             |                                               |               |  |
|  |-------------+-----------------------------------------------+---------------|  |
|  |  @bottom-l  |                                               |  @bottom-r    |  |
|  +-----------------------------------------------------------------------------+  |
|  |                          @bottom-center margin box                          |  |
|  +-----------------------------------------------------------------------------+  |
+-----------------------------------------------------------------------------------+

Technical Deep Dive & Specifications

1. The @page Rule Syntax & Dimensions

The @page at-rule establishes properties for the page box. It accepts dimensions, orientation keywords, and margin values:

@page {
  /* Standard paper size keyword + optional orientation */
  size: A4 portrait; /* or 'letter landscape', 'legal', etc. */
  
  /* Exact physical dimensions */
  /* size: 210mm 297mm; */
  /* size: 8.5in 11in; */

  /* Page margins */
  margin-top: 20mm;
  margin-right: 15mm;
  margin-bottom: 20mm;
  margin-left: 15mm;
}

Standard Paper Size Reference Table

Keyword Physical Dimensions (Metric) Physical Dimensions (Imperial) CSS 96 DPI Pixels Common Region
A4 $210\text{ mm} \times 297\text{ mm}$ $8.27\text{ in} \times 11.69\text{ in}$ $793.7\text{ px} \times 1122.5\text{ px}$ International Standard (ISO 216)
letter $215.9\text{ mm} \times 279.4\text{ mm}$ $8.5\text{ in} \times 11.0\text{ in}$ $816\text{ px} \times 1056\text{ px}$ North America (US, Canada)
legal $215.9\text{ mm} \times 355.6\text{ mm}$ $8.5\text{ in} \times 14.0\text{ in}$ $816\text{ px} \times 1344\text{ px}$ Legal Contracts (North America)
A3 $297\text{ mm} \times 420\text{ mm}$ $11.69\text{ in} \times 16.54\text{ in}$ $1122.5\text{ px} \times 1587.4\text{ px}$ Large Format Posters / Blueprints

2. Page Pseudo-Classes (:first, :left, :right, :blank)

The CSS Paged Media specification provides pseudo-classes to customize specific sheets in a multi-page document:

/* Universal defaults */
@page {
  size: A4;
  margin: 20mm;
}

/* 1. Cover Page (Sheet 1) */
@page :first {
  margin-top: 0;
  margin-bottom: 0;
  /* Often zero margin for full-bleed cover background */
}

/* 2. Left-hand / Even pages (Verso) in a bound book */
@page :left {
  margin-left: 15mm;  /* Outer edge */
  margin-right: 25mm; /* Inner gutter for bookbinding spine */
}

/* 3. Right-hand / Odd pages (Recto) in a bound book */
@page :right {
  margin-left: 25mm;  /* Inner gutter for bookbinding spine */
  margin-right: 15mm; /* Outer edge */
}

/* 4. Blank pages generated by page break padding */
@page :blank {
  @top-center { content: none; }
  @bottom-center { content: none; }
}
       LEFT-HAND PAGE (:left)                    RIGHT-HAND PAGE (:right)
+-------------------+-------------------+   +-------------------+-------------------+
|  Margin: 15mm     |  Gutter: 25mm     |   |  Gutter: 25mm     |  Margin: 15mm     |
|  (Outer)          |  (Spine)          |   |  (Spine)          |  (Outer)          |
|                   |                   | S |                   |                   |
|   Text Body       |                   | P |                   |   Text Body       |
|   Even Page       |                   | I |                   |   Odd Page        |
|                   |                   | N |                   |                   |
|                   |                   | E |                   |                   |
+-------------------+-------------------+   +-------------------+-------------------+

3. Named Pages (Switching Orientations Mid-Document)

You can assign named @page contexts to specific HTML elements to dynamically switch paper size or orientation within the same document:

/* Default page is Portrait */
@page {
  size: A4 portrait;
  margin: 20mm;
}

/* Define a specialized landscape named page */
@page landscape-sheet {
  size: A4 landscape;
  margin: 15mm;
}

/* Attach the named page to an element */
.financial-ledger-table {
  page: landscape-sheet;
  break-before: page;
  break-after: page;
}

๐Ÿ’ป Interactive Code Playground

Below is a complete, runnable HTML document demonstrating named pages, cover page margin resets, and portrait-to-landscape transitions.

Starter Code

Line-by-Line Code Breakdown

  • Lines 50โ€“53 (@page): Establishes standard A4 portrait ($210\text{mm} \times 297\text{mm}$) with a standard $20\text{mm}$ border margin.
  • Lines 56โ€“58 (@page :first): Targets the very first sheet in the document stack and sets margin to 0, allowing cover graphics to bleed directly to the sheet boundary.
  • Lines 61โ€“64 (@page wide-table-page): Defines a custom named page with size: A4 landscape and reduced $15\text{mm}$ margins.
  • Lines 79โ€“81 (.landscape-section): Assigns the page: wide-table-page; property to the container, instructing the print layout engine to trigger a page break and rotate the virtual paper by 90 degrees.
  • Lines 72โ€“77 (.page-sheet): Enforces break-after: page; (with legacy fallback page-break-after: always;) so every visual sheet starts on a fresh physical page.

Expected Browser Render Output

  • Screen View: Displays three neat, centered paper sheets with drop shadows over a slate-gray background. Sheet 1 is dark, Sheet 2 is portrait white, and Sheet 3 is a wide landscape sheet.
  • Print Preview (Cmd/Ctrl + P):
    • Page 1 prints in portrait with edge-to-edge dark theme.
    • Page 2 prints in portrait with $20\text{mm}$ margins.
    • Page 3 automatically rotates into landscape format, cleanly displaying all 8 columns without horizontal clipping or font shrinking.

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45ยฐC
INSPECTING DOM: VALID
TAGS: SCANNING...

๐Ÿ‹๏ธ Hands-On Exercise

๐ŸŽฏ The Challenge: Bookbinding Gutter Layout

Scenario: You are publishing an academic whitepaper that will be printed double-sided and spiral-bound. If you use equal $15\text{mm}$ left and right margins, the spiral binding will drill holes directly through the text on the inside edges.

Instructions:

  1. Configure an @page base rule with standard letter portrait paper.
  2. Use @page :first to remove headers and provide a balanced $20\text{mm}$ margin for the cover title.
  3. Configure @page :left (even pages) with a $25\text{mm}$ right margin (inner spine) and a $15\text{mm}$ left margin (outer edge).
  4. Configure @page :right (odd pages) with a $25\text{mm}$ left margin (inner spine) and a $15\text{mm}$ right margin (outer edge).

๐Ÿ Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45ยฐC
INSPECTING DOM: VALID
TAGS: SCANNING...

โš ๏ธ Common Pitfalls

  1. Mixing margin on body with @page Margins: If you set margin: 20mm in @page AND margin: 20px or padding: 2rem on body, they add together! In print stylesheets, always set body { margin: 0; padding: 0; } and let @page { margin: ... } exclusively control the paper margins.
  2. Assuming @page Applies to Screen Media: The @page rule has zero effect on standard browser window rendering. It is only evaluated when generating print previews, physical prints, or PDFs.
  3. Relying on Default Browser Margins: If you omit @page { margin: ... }, browsers apply unpredictable default margins ($0.4\text{in}$ to $0.75\text{in}$) depending on the user's operating system and printer driver. Always declare explicit @page margins for deterministic rendering.

๐Ÿ’ก Pro Tips

  1. Use Millimeters for International Layouts: While US developers default to in, international document specifications (ISO 216) are defined in millimeters. Setting @page { size: A4; margin: 15mm; } avoids rounding inaccuracies across international rendering engines.
  2. Implement Bleed and Crop Marks for Professional Presses: If you are outputting HTML/CSS for professional offset printing presses, use @page { bleed: 3mm; marks: crop cross; } (supported in commercial PDF engines like PrinceXML and WeasyPrint).
  3. Combine Named Pages with Landscape Charts: Keep the majority of your corporate document portrait, but isolate wide financial tables, architectural diagrams, and Gantt charts onto named landscape pages using page: landscape-page; break-before: page;.

๐Ÿ“Œ Key Takeaways

  • The @page rule configures paper size (A4, letter, legal), orientation (portrait, landscape), and page-level margins.
  • @page :first targets the initial document page (ideal for zero-margin full-bleed covers).
  • @page :left and @page :right enable asymmetric gutter margins for duplex bookbinding.
  • Named pages (page: page-name;) permit switching orientation mid-document for wide data tables.
  • Always reset body { margin: 0; padding: 0; } in print mode to prevent margin double-stacking.
  • --
โญ LEARN: HTML ๐ŸŒŸ โš”๏ธ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

Which @page declaration correctly configures a document to print on standard North American letter paper in landscape orientation with 0.5-inch margins?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

When formatting a double-sided printed manual for spiral binding, which pseudo-class should receive a larger margin-right to accommodate the spine?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

How do you trigger a specific section of an HTML document to render on a custom landscape page named chart-page?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP