html - 分页符上的 CSS 边距
问题描述
我正在开发一个小型个人网站,该网站也需要可打印。该站点本身的结构很简单:body
用作背景,有一个具有固定宽度(以及一些样式、填充等)的容器子容器,在这个容器中,我有几个部分 ( <div class="section">
)。在打印期间,我宁愿不分解这些部分,除非有必要(因此,.section
有一个样式添加page-break-inside: avoid;
)。显然,如果这样的部分不能放入单个页面,它将在内部有一个分页符,否则会将元素滑动到下一页。
这部分工作正常,但是在分页后,我仍然希望下一个元素与页面顶部正确对齐,并使用其默认边距。但这并没有发生。每当我准备打印时,.section
被推到下一页的元素顶部的边距消失 - 即使它不应该消失,除非我对分页符和边距的理解不正确(可能是这种情况)。
我准备了一个小例子:
body {
background: none repeat scroll 0 0 #eee;
margin: 0;
color: #4a4a4a;
display: block;
}
.container {
margin: 16px auto;
padding: 2.5% 0;
max-width: 200mm;
line-height: 1.1;
border-radius: 16px;
background-color: #fff;
color: #fff;
}
.container>.section {
padding: 3%;
margin: 5% 2.5%;
min-height: 500px;
border-radius: 16px;
box-shadow: 0px 4px 8px 0px #AA888888;
}
.container>.section:first-of-type {
margin-top: 0%;
}
.container>.section:last-of-type {
margin-bottom: 0%;
}
.section-red {
background-color: #f44336;
background-repeat: repeat;
}
.section-green {
background-color: #8bc34a;
background-repeat: repeat;
}
.section-blue {
background-color: #03a9f4;
background-repeat: repeat;
}
.section-yellow {
background-color: #c0ca33;
background-repeat: repeat;
}
.section-orange {
background-color: #ffb300;
background-repeat: repeat;
}
.section-pink {
background-color: #e91e63;
background-repeat: repeat;
}
.section-purple {
background-color: #9c27b0;
background-repeat: repeat;
}
.font-size-large {
font-size: 14px !important;
}
.font-size-xlarge {
font-size: 18px !important;
}
@media print {
body {
width: 210mm;
}
.container {
max-width: 90%;
min-width: 0;
margin: 5mm auto 200mm;
}
.container > .section {
page-break-inside: avoid;
margin-top: 8px;
}
.container > .section > section {
page-break-inside: avoid;
}
}
<html>
<head>
</head>
<body>
<div class="container font-size-large">
<div class="section section-red">
</div>
<div class="section section-blue">
</div>
<div class="section section-green">
</div>
<div class="section section-purple">
</div>
<div class="section section-orange">
</div>
</div>
</body>
</html>
不过,您可能需要将其复制到本地 HTML 和 CSS 文件才能正确打印。
编辑:
问题的快速视觉示例。
解决方案
我在这里的相关上下文中找到了一个解决方案,它也适用于这种情况。 box-decoration-break :clone 用于在发生行、列或分页时“复制”css 属性。后者是这里的情况,因为边距和/或填充是复制的属性之一。(除了 iexplore 之外,它得到了广泛的支持。)
我所要做的就是将该属性添加到我的 print-css 中,以便在每个页面上为主元素(即您的 .container)提供一个固定的标题和一个重复的填充:
@media print {
header {
display: flex;
flex-flow: wrap;
position: fixed;
top: 0;
left: 0;
right: 0;
}
main{
padding: 4cm 2cm 2cm 2cm;
box-decoration-break: clone;
}
...
}
...
推荐阅读
- javascript - How do you add a Fontawesome icon to a button in a JavaScript function
- python - 为什么 Python 3.8 将像 "\x48" 这样的字符串解释为 "H"。我想把它写成字符串中的“\x48”
- rust - 25519-dalek 的主要补充?
- pyspark - 在 pyspark 中聚合 Kolmogrov Smirnov 测试
- ssl - 用作 https 的反向代理时,nginx 行为缓慢
- html - 如何根据父容器内的可用空间在我的元素之间分配相同的高度?(我需要动态解决方案)
- javascript - 画布:删除对象后恢复图像
- python - python entry_point 没有模块名称 __main__
- excel - 运行时错误 5 无效的过程调用或参数
- sql - 计算和平均范围