Explain Codes LogoExplain Codes Logo

Avoid page break inside row of table

html
responsive-design
css-grid
page-break-inside
Anton ShumikhinbyAnton Shumikhin·Dec 18, 2024
TLDR

Keeping a table row intact on a printed page is accomplished using CSS page-break-inside: avoid; on tr:

tr { page-break-inside: avoid; }

This prompts the printer to consider each row an uninterruptable unit, ensuring they remain grouped on a single page.

However, the journey doesn't end there. Let's dig a bit deeper to enhance this concept, focus on print-friendly designs, and address some common scenarios.

CSS and printing: The perfect marriage

Setting up a print-friendly CSS class can elevate the quality of print outputs by applying specific style rules during printing.

@media print { .print-friendly tr { page-break-inside: avoid; } }

Tackling complex tables

Complex tables may require additional alterations to maintain structure and aesthetics in print layout:

  1. Spotless borders: Use border-collapse: collapse; on tables to avoid border shenanigans caused by display changes during print.

  2. Brains over wrap: Apply white-space: nowrap; on table cells to prevent the contents from wrapping and causing potential row breaks.

  3. Print layout gymnastics: Change tr display properties within a @media print query, but avoid show-offs like inline-block or flex that can overshadow table layout.

  4. Browser comportment: Browsers such as Chrome have distinct behaviors regarding page breaks. Always cross-check your print layouts in multiple browsers to avoid getting "chrome-zoned".

A CSS cocktail for better print layouts

Employing a blend of CSS properties can enhance a page-break-inside: avoid party:

  • An end to duplicates: The 4px trick with pseudo-elements prevents the issue of double borders often seen with tr display changes.
@media print { .print-friendly tr:before, .print-friendly tr:after { /* Creating a 4px invisible shield. */ content: ""; display: block; height: 4px; } }
  • Content flow retention: Using a div with page-break-inside: avoid in each td while giving it some breathing space in the form of margin stops breaks from occurring too closely to the text.
@media print { .print-friendly td div { margin: 4px; /* The ultimate 'put an end' to awkward spaces. */ } }

Embracing the modern CSS world

For the adventurous, there's always an option to switch gears and leverage CSS Grid for advanced layouts:

@media print { .print-grid-container { /* Making gridding cooler, one print at a time. */ display: grid; } }

While CSS Grid isn't the de facto choice for tabular data, its flexibility gives it the edge in print styling. As always, double-check to ensure no unintended side-effects.

In a case where tables traverse multiple pages, repeating headers on each page ensures readability. It's like drawing the map on every page:

thead { display: table-header-group; }