Search code examples
javascripthtmlcssprintingmedia-queries

how can we prevent a block from being printed across different pages


On my website, I'd like divB to be printed right after divA. But if the content of divB implies divB is printed on two pages, I'd like to insert a page break before so that divB is not printed on two pages but only one.

How can I do that with css ideally, javascript otherwise ?

Thanks a lot !

EDIT :

In the following, divB is to large so it will be breaked on two pages. I then want to insert a page break before divB so it prints on a different page.

BUT If divA and divB are small enough to stay on same page, I don't want a page break.

enter image description here


Solution

  • There is no good general solution. As some have pointed out, you can put a page break before <div> "B" ... but there you will always get it. Even when "A" and "B" all fit on one page.

    You can use page-break-inside="avoid" on <div> "B". This is probably closer to what you want. If "B" does not fit on the page with "A", "B" will all be moved to the next page.

    BUT ... that has a side effect because there is a third possibility. What if the content of "B" is so large that it itself does not fit on a page? WHat will happen is that it would do what you think, moving "B" to the next page and try to build that page with "B". It will not be able to meet the condition that "B" avoid a page break inside so it will break that condition. Unfortunately, it would not figure that out until the end of the page, so you will end up with a blank page.

    If you know that "B" will always fit on one page, then you can use page-break-inside="avoid" and that would work. But if it does not, nothing will work for you.

    A slightly more lengthy explanation for a similar question is here:

    HTML/CSS: empty page + only header page when printing table

    So what you actually want is three things in one... (1) you would like it avoid a page-break inside as long as it is not longer than a page, otherwise, (2) you want a page break before (3) unless it fits on the current page. Unfortunately, this does not exist. You could only do that with Javascript. You could set the width for the page for the div's and then get the height of div "A" and div "B" and then make a decision to dynamically insert those CSS properties as part of the print process.