Page break inside flexbox container without breaking inside of items

Viewed 362

I am trying to use HTML & CSS to lay out PDFs / printable documents. I have written a template that uses flexboxes to resize a section of the document based on how many items their are. I have given example code at the bottom, but here is an outline and verbal description of the html:

  • Header (fixed on each page using position: fixed)
  • Content
    • Title
    • Section 1 (flexbox container)
      • 1 to 50 flexbox items (items are a fixed size and are set to wrap in rows)
    • Section 2
  • Footer (fixed on each page using position: fixed)

Three flexboxes can fit in a row and usually two rows can fit on a page. Section 2 is about the same height as the flexboxes so it takes the same space as a row.

For example, with 9 flexbox items in rows of 3: 6 should be on page 1 and 3 should be on page 2. However, with the code I have come up with, the flexbox container does not apply page breaks inside itself like its parent #content does. Here are images of #content properly page-breaking with 6 flexbox items: page 1 and page 2. And here is what happens with the flexbox container when it is too big to fit on one page (i.e. 9 flexbox items): page 1 and page 2. I have tried the break-{before,inside,after} attributes and they seem to be completely ignored.

The example images were generated on Chrome. Firefox behaves similarly, but will move the flexbox container to start at page 2 when it overflows. When testing the example code make sure you enable printing backgrounds.

@page {
  size: letter;
  margin: 0;
}

@media print {
  header,
  footer {
    position: fixed;
    left: 0;
    right: 0;
    z-index: 1;
  }
  header {
    top: 0.15in;
    bottom: auto;
  }
  footer {
    top: auto;
    bottom: 0.15in;
  }
  #content {
    position: relative;
    top: 0.5in;
  }
}

header,
footer {
  background-color: #d4ea6b;
  text-align: center;
}

#content {
  background-color: #8d1d75;
}

#content * {
  margin: 0.05in;
}

#title {
  text-align: center;
  background-color: #ffde59;
}

#container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  position: relative;
  break-inside: auto;
  background-color: #729fcf;
}

.item {
  width: 2.5in;
  height: 4in;
  background-color: #ff5429;
  text-align: center;
  break-inside: avoid;
}

#section-2 {
  break-inside: avoid;
  height: 4in;
  background-color: #77bc65;
}
<header>Header</header>
<div id="content">
  <p id="title">Title</p>
  <div id="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <div id="section-2"></div>
</div>
<footer>Footer<footer>

0 Answers
Related