Mastering CSS Paged Media for Print Layouts

CSS Paged Media

CSS Paged Media is a powerful feature of CSS that enables web developers to format content specifically for printed pages and other paged media. This functionality is particularly beneficial for creating documents intended for print, such as books, reports, or brochures.

Key Concepts

  • Paged Media: This refers to content that is divided into pages, resembling a printed book. Each page can have distinct styles and layouts.
  • Page Breaks: Several properties help control how content breaks between pages.
    • page-break-before: Forces a page break before the specified element.
    • page-break-after: Forces a page break after the specified element.
    • page-break-inside: Prevents a page break from occurring within the element.
  h1 {
      page-break-before: always; /* Forces a new page before each h1 */
  }

@page Rule: This CSS rule defines the dimensions and margins of a printed page, allowing adjustments to the content's appearance during printing.

  @page {
      size: A4; /* Specifies the page size */
      margin: 2cm; /* Sets the margin for the page */
  }

Key Properties

  • size: Defines the size of the page (e.g., A4, letter).
  • margin: Sets the margins for the page.
  • break properties: Control how content breaks across pages.

Example

Here’s a simple example demonstrating the use of CSS Paged Media:

@page {
    size: A4;
    margin: 1in;
}

h1 {
    page-break-before: always; /* Each h1 starts on a new page */
}

p {
    page-break-inside: avoid; /* Avoid breaking paragraphs across pages */
}

Conclusion

CSS Paged Media empowers developers with enhanced control over content presentation on printed pages. By effectively utilizing the @page rule and page break properties, one can create well-structured, printer-friendly layouts essential for producing high-quality printed documents directly from web content.