首页 > 解决方案 > 分页符上的 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 文件才能正确打印。

编辑:

问题的快速视觉示例。

常规页面,无中断(预期布局): 完整的布局

打印时布局损坏: 破碎的布局

标签: htmlcssmarginpage-break

解决方案


我在这里的相关上下文中找到了一个解决方案,它也适用于这种情况。 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;
    }
...
}
...

推荐阅读