gpt4 book ai didi

css - `page-break-after: avoid` 当边距发生中断时

转载 作者:行者123 更新时间:2023-11-28 19:24:10 34 4
gpt4 key购买 nike

从 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似乎说这不应该发生:

In the normal flow, page breaks can occur at the following places:

1) In the vertical margin between block-level boxes. When an unforced page break occurs here, the used values of the relevant 'margin-top' and 'margin-bottom' properties are set to '0'. When a forced page break occurs here, the used value of the relevant 'margin-bottom' property is set to '0'; the relevant 'margin-top' used value may either be set to '0' or retained.

...

  • Rule A: Breaking at (1) is allowed only if the 'page-break-after' and 'page-break-before' properties of all the elements generating boxes that meet at this margin allow it, which is when at least one of them has the value 'always', 'left', or 'right', or when all of them are 'auto'.

这是正常工作吗?还是 Chrome 的 CSS 中的错误?还是我的误会?

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

最佳答案

第一个(简单且安全的)解决方案:在 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

关于css - `page-break-after: avoid` 当边距发生中断时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56687274/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com