If you used HTML 5 <article>
and <header>
, here's a hack that seems to work with Webkit, Blink and Gecko (tweak the value 8rem
to match your needs):
article > header::before
{
content: "";
display: block;
height: 8rem; /* pretend that the header is at least 8rem high so this header cannot fit near the end of page */
margin-bottom: -8rem; /* however, reduce the margin the same amount so that the following content can stay in its usual place */
page-break-inside: avoid;
break-inside: avoid;
}
This works because pseudoelement ::before
is rendered downwards from top of the header and browsers do support page-break-inside: avoid;
well enough to actually reserve the space at the end of the page. It also uses the fact that browsers consider the height
without margins when the space required is actually measured. I don't know if this is specified in any spec or just happens to match the real world browser behavior.
Some of the other answers suggest using ::after
instead but in my experience that may result in cases where the container element <article>
starts to render on the previous page. Using ::before
seems to work better and the start of container element also seems to move. Obviously, the difference doesn't matter if your containing element doesn't have visible edges.
Note that because you have exactly one pseudo-element ::before
you might not be able to use this hack if you want to apply some other styles for ::before
. This hack requires that the ::before
is rendered under the other content but transparent so it cannot contain visible content.
Additional things to consider:
- The
page-break
nor page-break-inside
do not work inside tables (display:table
), display:grid
nor display:flex
. It's still unknown if this is caused by partial browser implementation or due CSS specification actually requiring this. In practice you need to use display:block
for all the parent elements up to <html>
or page breaks will happen anywhere.
- You cannot limit the reserved space to height of full container element. For example, if the whole
<article>
in the above example is less than 8rem
high, the element will still skip to next page because this hack blindly reserves space for 8rem
before even trying to fit the <article>
on the page.
However, in practice this works better than break-after:avoid
or page-break-after:avoid
due real world browser support. Also, the support for widows
and orphans
is really poor, so you may want to apply similar hack for <p>
element, too. I would suggest 2rem
or 3rem
space for those.
page-break-after: avoid
to the children of the elements it's applying to? So it's not just on the parent (for instance, on theul
plus theli
s? – Genealogypage
margins). So my proposed solution is to use Microsoft Edge to print your document. (To be fair, @page
margins are supported by WebKit browsers as well). – Kerr