我正在尝试用一些很长的表格制作一个可打印的文档。有时页面结束在表头和数据之间,这使得它更难阅读。
我怎样才能避免这种情况?
我尝试使用以下 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>
最佳答案
我根据此处建议的解决方案找到了解决此问题的方法:How do I avoid a page break immediately after a heading
向您的表格添加一个包装器并向其添加一个 before 伪元素。这个元素实际上不会占用任何空间(由于负边距底部),但它的高度将在计算分页符的位置时使用,如果太近则强制浏览器将表格推到下一页到底部。
200px 应替换为略大于标题高度 + 正文第一行高度的值。
/* This is the solution */
.wrapper::before {
content: "";
display: block;
height: 200px;
margin-bottom: -200px;
page-break-inside: avoid;
break-inside: avoid;
}
/* Table styles */
table {
width: 100%;
}
thead {
background: green;
}
thead tr {
page-break-inside: avoid;
break-inside: avoid;
}
tbody {
background: yellow;
}
tbody tr {
height: 80px;
}
td {
height: 80px;
}
<div class="wrapper">
<table>
<thead>
<tr>
<td>header</td>
<td>header</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
关于html - 如何避免 <thead> 和 <tbody> 之间的分页符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154720/