CSS Printing: Avoiding cut-in-half DIVs between pages?

joeylange picture joeylange · May 25, 2009 · Viewed 129k times · Source

I'm writing a plug-in for a piece of software that takes a big collection of items and pops them into HTML in a WebView in Cocoa (which uses WebKit as its renderer, so basically you can assume this HTML file is being opened in Safari).

The DIVs it makes are of dynamic height, but they don't vary too much. They're usually around 200px. Anyway, with around six-hundred of these items per document, I'm having a really rough time getting it to print. Unless I get lucky, there's an entry chopped in half at the bottom and top of every page, and that makes actually using printouts very difficult.

I've tried page-break-before, page-break-after, page-break-inside, and combinations of the three to no avail. I think it might be WebKit not properly rendering the instructions, or maybe it's my lack of understanding of how to use them. At any rate, I need help. How can I prevent the cutting-in-half of my DIVs when printing?

Answer

Dmitri Farkov picture Dmitri Farkov · May 25, 2009

Using break-inside should work:

@media print {
  div {
    break-inside: avoid;
  }
}

It works on all major browsers:

  • Chrome 50+
  • Edge 12+
  • Firefox 65+
  • Opera 37+
  • Safari 10+

Using page-break-inside: avoid; instead should work too, but has been exactly deprecated by break-inside: avoid.