Restrict the number of rows in a table to be printed in a page using CSS

6.2k views Asked by At

I am having a table in a web page, I need to restrict the number of rows in the table per page (say, each printed page should contain 10 rows) (only in the printed page).

My code is like this:

<style>
@media print {
   thead {display: table-header-group;}
}
</style>
<table>
   <thead>
      <tr>
         <th>First Heading</th>
         <th>Second Heading</th>
         <th>Third Heading</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>foo</td>
         <td>bar</td>
         <td>21</td>
      </tr>
            ....
            ....
</tbody>
</table>

I want to know, is there any possible way to do this using CSS or equivalent way?. Also i'm having an integer values in the 3rd row, i need to print the sum of those rows in each page (say, sum of 10 rows in each page at the end of the page).

Please suggest me some ideas to achieve this. All those to be done only in the printed page not in browser display.

2

There are 2 answers

8
Octfx On BEST ANSWER

You could use the nth-child() selector:

@media print {
  tr:nth-of-type(10n){
    page-break-after: always;
  }
}

This will not work in Chrome, since Chrome requires that a page-break element has to be a block level element.

There is currently no way to sum the content of a column with pure CSS, you would have to use some javascript or server-side processing.
Example:

  jQuery(document).ready(function(){
    x=0;
    i=0;
    items=jQuery( "tbody tr" ).length;
    jQuery( "tbody tr" ).each(function(index) {
      i++;
      x = x + parseInt(jQuery("td:last-of-type",this).text());
      if (i==10 || items == index+1){
        jQuery('<tr><td colspan="2">Total:</td><td>' + x + '</td></tr>').insertAfter(this);
        x=0;
        i=0;
      }
    });
  });

You would then have to increase tr:nth-of-type(10n) to tr:nth-of-type(11n) since this will add a row.

1
Vaibs_Cool On

Try this

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

FIDDLE DEMO