2017-05-24 66 views
1

我想用一些很長的表格來製作一個可打印的文檔。有時頁面會在表格標題和數據之間結束,這使得閱讀變得更加困難。如何避免<thead>和<tbody>之間的分頁符

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> 

回答

0

應用分頁到一個塊級僞元素對你tbody而不是將其直接向tbody。 這裏是工作Demo

您必須仔細定義您的頁面上下文和適當的邊距和尺寸以適合您的使用情況。

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;   
 
    } 
 
    
 
    
 
}
<div> 
 
    <a href="#" onClick="window.print();">Print</a> 
 
</div> 
 
<hr /> 
 
<table> 
 
    <thead> 
 
\t \t <tr> 
 
\t \t \t <th>Head 1</th> 
 
\t \t \t <th>Head 2</th> 
 
\t \t \t <th>Head 3</th> 
 
\t \t </tr> 
 
    </thead> 
 
\t <tbody> 
 
\t \t <tr> 
 
\t \t \t <td>Row 1 Cell 1</td> 
 
\t \t \t <td>Row 1 Cell 2</td> 
 
\t \t \t <td>Row 1 Cell 3</td> 
 
\t \t </tr> 
 
\t \t <tr> 
 
\t \t \t <td>Row 2 Cell 1</td> 
 
\t \t \t <td>Row 2 Cell 2</td> 
 
\t \t \t <td>Row 2 Cell 3</td> 
 
\t \t </tr> 
 
\t </tbody> 
 
\t <tbody> 
 
\t \t <tr> 
 
\t \t \t <td>Row 3 Cell 1</td> 
 
\t \t \t <td>Row 3 Cell 2</td> 
 
\t \t \t <td>Row 3 Cell 3</td> 
 
\t \t </tr> 
 
\t \t <tr> 
 
\t \t \t <td>Row 4 Cell 1</td> 
 
\t \t \t <td>Row 4 Cell 2</td> 
 
\t \t \t <td>Row 4 Cell 3</td> 
 
\t \t </tr> 
 
\t </tbody> 
 
    <tfoot> 
 
\t \t <tr> 
 
\t \t \t <th>Foot 1</th> 
 
\t \t \t <th>Foot 2</th> 
 
\t \t \t <th>Foot 3</th> 
 
\t \t </tr> \t 
 
    </tfoot> 
 
</table>

相關問題