如何避免和之间的分页

时间:2017-05-24 09:44:05

标签: html css html-table

我试图用一些很长的表格制作一个可打印的文档。有时页面在表头和数据之间结束,这使得它更难阅读。

Example

我怎么能阻止它?

我尝试使用以下CSS,但它没有帮助。

@media print {
        h1, h2, h3, thead, thead>tr {
            page-break-after: avoid;
            page-break-inside: avoid;
        }

        tbody {
            page-break-before: avoid;
        }

        /* I would also like to not have page breaks within first five rows */
        tbody:nth-child(-n+5) {    
            page-break-before: avoid;
        }
}

表格结构:

<table border="1" cellspacing="0" cellpadding="3">
    <thead>
    <tr>
        <th rowspan="2">Metric</th>
        <th colspan="3">Type 1</th>
        <th colspan="3">Type 2<th>
    </tr>
    <tr>
        <th>Initial</th>
        <th>Final</th>
        <th>Difference</th>
        <th>Initial</th>
        <th>Final</th>
        <th>Difference</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>Dataset1</td>
        <td>*DATA*</td>
        ...
    </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

将分页符应用于tbody上的块级伪元素,而不是直接将其应用于tbody。 这是工作Demo

您必须仔细定义页面上下文以及适合您的用例的边距和尺寸。

&#13;
&#13;
table, th, td { border: 1px solid gray; border-collapse: collapse; }
th, td { padding: 8px; }
tbody:first-of-type { background-color: #eee; }

@page {
    size: A4;
    margin: 0;
}
@media print {
    html, body {
        width: 210mm;
        height: 297mm;
    }
    tbody::after {
        content: ''; display: block;
        page-break-after: always;
        page-break-inside: avoid;
        page-break-before: avoid;        
    }
    
  
}
&#13;
<div> 
    <a href="#" onClick="window.print();">Print</a>
</div>
<hr />
<table>
    <thead>
		<tr>
			<th>Head 1</th>
			<th>Head 2</th>
			<th>Head 3</th>
		</tr>
    </thead>
	<tbody>
		<tr>
			<td>Row 1 Cell 1</td>
			<td>Row 1 Cell 2</td>
			<td>Row 1 Cell 3</td>
		</tr>
		<tr>
			<td>Row 2 Cell 1</td>
			<td>Row 2 Cell 2</td>
			<td>Row 2 Cell 3</td>
		</tr>
	</tbody>
	<tbody>
		<tr>
			<td>Row 3 Cell 1</td>
			<td>Row 3 Cell 2</td>
			<td>Row 3 Cell 3</td>
		</tr>
		<tr>
			<td>Row 4 Cell 1</td>
			<td>Row 4 Cell 2</td>
			<td>Row 4 Cell 3</td>
		</tr>
	</tbody>
    <tfoot>
		<tr>
			<th>Foot 1</th>
			<th>Foot 2</th>
			<th>Foot 3</th>
		</tr>	
    </tfoot>
</table>
&#13;
&#13;
&#13;