`page-break-after:避免'当页边空白发生时

时间:2019-06-20 13:39:35

标签: css google-chrome

从Chrome浏览器打印时,我希望避免在标题和下一段之间出现分页。

对于大多数文档,我都做到了:

h1 {
   page-break-inside: avoid;
   page-break-after: avoid;
}

...,这将移动一堆分页符,并在必要时强制在标题之前进行分页。

但是,当中断发生在标题的空白处时,这似乎失败了。

我可以这样复制:

<html>
   <head>
     <style>
         h1 {
           border-style: solid;
           margin: 30px;
           page-break-inside: avoid;
           page-break-after: avoid;
         }
         p {
           background-color: grey;
         }
     </style>
   </head>
   <body>
     <h1>Lorem ipsum dolor sit amet</h1>
     <p>... consectetur adipiscing elit (etc)...</p>
     (Repeat to fill a page)
</html>

...缩短/延长段落文本,直到打印预览显示不需要的分页符:

screenshot of unwanted page break

CSS spec似乎说这不应该发生:

  

在正常流程中,分页符可能发生在以下位置:

     

1)在块级框之间的垂直边距中。当无力时   在此发生分页符,相关“ margin-top”的使用值   和'margin-bottom'属性设置为'0'。当强制页面   此处发生中断,相关“ margin-bottom”的使用值   属性设置为“ 0”;相关的“保证金最高”使用价值可能   可以设置为“ 0”或保留。

...

  
      
  • 规则A:只有在'page-break-after'和   所有元素生成框的“ page-break-before”属性   满足此边距允许,这是其中至少一个   具有值“总是”,“左”或“右”,或者当它们全部为   “自动”。
  •   

这是否应该正常工作?还是Chrome的CSS中存在错误?还是我误会了?

我能以某种方式解决它吗?

1 个答案:

答案 0 :(得分:0)

第一个(简单且安全的)解决方案: 在h1和第一段周围添加一个section / div元素,并在其上设置page-break-inside: avoid。例如:

    <body>
       <div class="headline">
          <h1>A sample title</h1>
          <p>First paragraph bla bla blac....</p>
       </div>
       <p>Second paragraph...</p>
    </body>

使用CSS:

    .headline {
        page-break-inside: avoid;
    }

第二个解决方案:对html进行少量更改,语义section可以执行以下操作:

  <body>
    <div class="page">
      <section>
        <h1>
          A Simple Title
        </h1>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure dolor in
          reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
          pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est laborum.
        </p>
        ...
        <h1>Second title</h1>
        <p>Lorem....</p>
    </section>
  </body>

使用CSS:

body {
  font: sans-serif;
}
.page {
  padding: 1em;
}
section {
  page-break-before: always;
}
section > p + h1 {
  page-break-before: always;
  page-break-after: avoid;
}
section > h1* + p {
  page-break-before: avoid;
}

您可以在此处查看示例:https://codesandbox.io/s/test-print-avoid-page-break-after-title-l4kbq