← Back to CSS Course | Chapter 9: Modern CSS Features | Lesson 19 of 25

CSS Pagination (Print)

Think of a book editor deciding exactly where each chapter should start on a fresh page, and making sure a table never gets sliced in half between two pages -- readers hate flipping back and forth to see the rest of a broken row. CSS pagination rules give the browser those same editorial instructions when it prints a webpage onto physical pages.

The @page Rule

@page defines styling that applies specifically to printed pages, most commonly setting page margins and page size, and is only meaningful inside a print stylesheet or print media query -- it has no effect on normal screen rendering.

Example: The @page Rule

css
@page {
  margin: 2cm;
  size: A4;
}

Named Pages and :first

The @page rule supports a :first pseudo-class for styling only the first printed page differently (e.g. a larger top margin for a cover page), and named page selectors let different sections of a document use different @page rules.

Example: Named Pages and :first

css
@page :first {
  margin-top: 5cm;
}

Controlling Breaks Before and After an Element

break-before and break-after (the modern replacements for the older page-break-before/page-break-after properties) force or avoid a page break immediately before or after a given element, commonly used to always start a new chapter or section on a fresh page.

Example: Controlling Breaks Before and After an Element

css
h1 {
  break-before: page;
}

Preventing an Element From Splitting: break-inside

break-inside: avoid tells the printer not to split a given element's content across two pages at all -- essential for tables, figures, or code blocks where a mid-content split would make the printed page unreadable.

Example: Preventing an Element From Splitting: break-inside

css
table {
  break-inside: avoid;
}

Widows and Orphans

widows and orphans control the minimum number of lines of a paragraph that must appear together at the top (widows) or bottom (orphans) of a page split, preventing the awkward typographic case of a single stray line left alone on a page.

Example: Widows and Orphans

css
p {
  widows: 3;
  orphans: 3;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.