π What Is @page?
The @page at-rule allows you to control the page boxwhen printing a webpage. It lets you style margins, size, orientation, and define different styles for left/right pages or first pages.
π¨οΈ In short: itβs CSS for printed documents.
π― What You Can Style with @page
- Page size (A4, Letter, custom dimensions)
- Margins
- Orientation (portrait/landscape)
- Different rules for first, left, or right pages
- Page bleed, marks (limited browser support)
π§© Basic Syntax
Basic @page Rule
@page {
margin: 20mm;
}This sets the default margin for printed pages to 20mm.
π Setting Page Size
Set Page Size
@page {
size: A4;
}Custom Size
@page {
size: 8.5in 11in; /* width height */
}β Useful for invoices, tickets, resumes, certificates, and printable layouts.
π Orientation (Portrait / Landscape)
Landscape Orientation
@page {
size: A4 landscape;
}π΄ Styling Page Margins
Set Margins
@page {
margin: 10mm 20mm;
}β Margins affect the entire printed page layout β You canβt style inside the margin directly β only margin boxes (limited support)
π Special Pseudo-Classes for @page
@page supports special pseudo-classes allowing different styling for specific pages.
1οΈβ£ First Page
First Page Styling
@page :first {
margin-top: 40mm;
}2οΈβ£ Left Page
Left Page Styling
@page :left {
margin-left: 30mm;
}3οΈβ£ Right Page
Right Page Styling
@page :right {
margin-right: 30mm;
}π‘ Useful for book-style printing where left/right pages differ.
π What You CANNOT Style in @page
- CSS layout inside page content (use normal CSS instead)
- Background images unless browser print settings allow it
- Most CSS properties (only margin, size, marks, bleed allowed)
- Selectors β only @page + pseudo-classes work
Note
π Real-World Example: Invoice Printing
Invoice Print Layout
/* Print styles */
@media print {
body {
font-family: sans-serif;
}
@page {
size: A4 portrait;
margin: 15mm;
}
@page :first {
margin-top: 30mm;
}
.no-print {
display: none !important;
}
}β Hides UI elements
β Adjusts page margins
β Ensures the first page has extra space for branding
ποΈ Using @page Inside @media print
Common Structure
@media print {
@page {
size: letter;
margin: 20mm;
}
h1 {
font-size: 24pt;
}
}π While @page can exist outside @media print, itβs generally best practice to keep it inside print media queries.
π Best Practices
- Use @page for print-specific layout only
- Always test printed output in multiple browsers
- Donβt rely on advanced print features β browser support varies
- Combine with @media print for full control
- Use millimeters (mm) for high precision