Page break on print with title

Viewed 32

I have a <table>.

table {
  page-break-inside: auto
}

tr {
  page-break-inside: avoid;
  page-break-after: auto
}

thead {
  display: table-header-group
}

tfoot {
  display: table-footer-group
}
<h2>Title</h2>
<table>
  <thead>
    <tr>
      <th>
        Test
      </th>
      <th>
        Test 2
      </th>
    </tr>
  </thead>
  <tbody>
    <td>
      Test
    </td>
    <td>
      Test 2
    </td>
  </tbody>
</table>
<h2>Another one</h2>
<table>
  <thead>
    <tr>
      <th>
        Test
      </th>
      <th>
        Test 2
      </th>
    </tr>
  </thead>
  <tbody>
    <td>
      Test
    </td>
    <td>
      Test 2
    </td>
  </tbody>
</table>
I want, when I print, that the title follows with the rest and breaks at the correct spot, because sometimes, the title stays at the end of a page, and the <table> sits on the other page.

1 Answers

Unfortunately, the page-break properties (and especially the avoid value) are not very well supported by most browsers.

In the meantime, you can use the following solution:

  • move your title inside your table by using the caption tag
  • add page-break-before: always; in your table element CSS

table {
  page-break-inside: auto;
  page-break-before: always; /* add this line */
}

tr {
  page-break-inside: avoid;
  page-break-after: auto;
}

thead {
  display: table-header-group;
}

tfoot {
  display: table-footer-group;
}
<table>
  <caption>
    <h2>Title</h2>
  </caption>
  <thead>
    <tr>
      <th>
        Test
      </th>
      <th>
        Test 2
      </th>
    </tr>
  </thead>
  <tbody>
    <td>
      Test
    </td>
    <td>
      Test 2
    </td>
  </tbody>
</table>
<table>
  <caption>
    <h2>Another one</h2>
  </caption>
  <thead>
    <tr>
      <th>
        Test
      </th>
      <th>
        Test 2
      </th>
    </tr>
  </thead>
  <tbody>
    <td>
      Test
    </td>
    <td>
      Test 2
    </td>
  </tbody>
</table>

Although this will work, please note that this solution is not the most sustainable, as you will potentially print more pages than necessary.

Also, don't forget to set the media attribute of your link tag to "print", like so:

<link rel="stylesheet" media="print" href="print.css">
Related