'Smart way to move elements into another element as soon as there is no space left

I am building a preview of a document, which is split into separate DIN-A4 Pages. Those A4-Pages are white blocks with a margin between them.

Now i need a way to move elements to the next page as soon as there is no space left on the current page.

I am currently thinking of implementing a solution using JavaScript to detect if an element is overflowing the current page (which can be checked with el.clientHeight < el.scrollHeight or similar things), and then mark that element and all following nodes to start on the next page. I dont think this will be the most beautiful approach since it will require multiple render cycles to get the result. Do you have any suggestions on how to solve this problem in a smart way?

I know CSS very well, and i don't think there is a way to solve this with flexbox, since flex cant move elements from one div (which is a page with white background) into another div.

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source