How do I avoid a page break immediately after a heading

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 22:14:40
Jason

Since the CSS property page-break-after: avoid doesn't work in any WebKit or Mozilla based browsers, use the page-break-inside: avoid over the heading and an acceptable amount of the text:

CSS

<style type="text/css">
    .nobreak {
        page-break-inside: avoid;
    }
</style>

HTML

<div class="nobreak">
    <h3>Heading!</h3>

    <p>Some things:</p>

</div>

    <ul>
      <li>Thing one</li>
      <li>Thing B</li>
      <li>Thing 4</li>
    </ul>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!