Reputation: 7902
I have a table that is being generated by means of a loop.
Each loop creates 2 rows of the table.
What I want to achieve is when this page is printed the the 2 rows created in each loop iteration stay together and do not get split over a page boundary.
I have tried applying the CSS rule {page-break-inside: avoid;}
on both the tr
and td
elements with not much luck (I hear this is an known issue with non-block elements).
Apart from rebuilding the view using divs, is there a solution that I can apply to the table?
Upvotes: 12
Views: 8776
Reputation: 895
Unfortunately CSS page break properties are not always reliable across all browsers and platforms.
For a more sure-fire approach, as AaA mentions, I find it better to wrap the rows that you don't want split into a table of their own.
Like so:
<table>
<thead>
//headers
</thead>
<tbody>
<tr> //Create your for loop on this element
<td>
<table>
<tbody>
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
Each table can be more reliably kept together as needed, and the table can have as many rows and columns needed.
Upvotes: 1
Reputation: 183
The discovery of the styles page-break-inside: avoid; page-break-before: auto
was very useful to me when looking for a way to do exactly this. However, I found a way of making it work without having to use separate tables. Wrap each set of rows that you want to keep together in a <tbody>
element, and give that element the two styles that control page breaks. As far as I can tell, that has exactly the desired effect: if the printed document is split across multiple pages, the rows within each <tbody>
element will always appear on the same page.
Upvotes: 0
Reputation: 3694
You need to combine these two styles together (although auto is the default value)
if those two rows are supposed to attach together, you might consider using a single table for each of those two rows instead of having a single table for all rows.
{page-break-inside: avoid;page-break-before:auto}
Also check comments for this answer
Upvotes: 10