Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid a page break immediately after a heading

I have an HTML 4.01/CSS 2.1 document that includes an H3 heading followed by a short (one line) paragraph block and then an unordered list with several items:

<h3>Heading!</h3>  <p>Some things:</p>  <ul>   <li>Thing one</li>   <li>Thing B</li>   <li>Thing 4</li> </ul> 

My problem is that when I print the document (or render it as a PDF using wkhtmltopdf), sometimes a page break will occur right after the heading, before the paragraph, which looks quite silly.

Is there a way to stipulate that page breaks should be avoided immediately after a header? (I'm not averse to HTML5/CSS3 solutions, if that simplifies things significantly.)

Note: following suggestions, I tried using the CSS property page-break-after: avoid. This doesn't really work in any WebKit or Mozilla based browsers, though.

like image 625
detly Avatar asked Feb 11 '12 08:02

detly


People also ask

How do you prevent page breaks?

On the Format menu, select Paragraph, and then select the Line and Page Breaks tab. Clear the Keep lines together, Keep with next, and Page break before check boxes.

How do I prevent page breaks within a table row?

Make sure all parent elements are display: block . Also consider overriding table , tr , td 's display styles with CSS grid for the print layout if you keep having issues with the table.

What is page-break After avoid?

always − A page break should be forced after this element's box. avoid − No page break should be placed after the element's box if at all possible. left − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a left-hand page.

How do I prevent a page-break in a div?

Syntax: page-break-inside: auto; avoid: It avoids a page break inside the element.


1 Answers

This is an extremely hacky solution, but it works for me:

h1 {     page-break-inside: avoid; } h1::after {     content: "";     display: block;     height: 100px;     margin-bottom: -100px; } 

Basically I create an invisible element that increases the size of the <h1> without affecting the content after it. When page-break-inside: avoid is applied and the whole <h1> (including the hacky element cannot fit into the page) the browser is forced to carry the <h1> to the next page.

like image 84
Zenorbi Avatar answered Oct 02 '22 15:10

Zenorbi