Back to blog
March 17, 202612 min read

CSS Print Styles: Making Your HTML Look Perfect in PDF

Master @page rules, page breaks, margins, headers/footers, and other CSS techniques for pixel-perfect PDF output.

cssprint-styles@pagepage-breaks

The @page rule

The @page rule controls page-level properties:

@page {
  size: A4;                    /* or Letter, Legal, or custom WxH */
  margin: 20mm 15mm;           /* top/bottom, left/right */
}

@page :first {
  margin-top: 40mm;            /* Extra top margin on first page */
}

@page :left {
  margin-left: 25mm;           /* Binding margin for left pages */
}

@page :right {
  margin-right: 25mm;          /* Binding margin for right pages */
}

Page breaks

/* Force a page break before this element */
.chapter { break-before: always; }

/* Prevent this element from being split across pages */
.card { break-inside: avoid; }

/* Keep at least 3 lines at the bottom of a page */
p { orphans: 3; widows: 3; }

Headers and footers with @page margin boxes

@page {
  @bottom-center {
    content: "Page " counter(page) " of " counter(pages);
    font-size: 9pt;
    color: #999;
  }

  @top-right {
    content: "Confidential";
    font-size: 8pt;
    color: #ccc;
  }
}

Print-specific styles

@media print {
  .no-print { display: none; }
  body { font-size: 11pt; }
  a { text-decoration: none; color: inherit; }
  .page-break { break-before: always; }
}

Full bleed (edge-to-edge content)

@page { margin: 0; }
body { margin: 0; padding: 0; }
.cover {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea, #764ba2);
}

All of this is standard CSS. No proprietary extensions. No special syntax. If you can write CSS for a web page, you can write CSS for a PDF. pdfRelay's Rust engine supports flexbox, grid, custom fonts, gradients, shadows, and all the modern CSS features you'd expect.

Ready to try pdfRelay?

Get started free. No credit card required.