在開發網頁列印功能時,常使用 CSS 的 page-break-after: always 強制分頁。然而,該屬性在 Internet Explorer 中運作正常,但在 Firefox(甚至 Chrome)中卻失效,特別是套用在 <tr> 表格列上時。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>分頁列印</title>
</head>
<body>
<object id=WebBrowser classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height=0 width=0 ></object>
<table border="0" style="font-size:9pt;" width="300px" align="center">
<thead style="display:table-header-group; font-weight:bold">
<tr>
<td colspan="2" align="center" style="font-weight:bold; border:3px double red"> 每頁都有的表頭 </td>
</tr>
</thead>
<tbody>
<tr><td>表格內容</td><td>表格內容</td></tr>
...
<tr style="page-break-after: always;">
<td>在這個之後分頁</td> <td>在這個之後分頁</td>
</tr>
...
</tbody>
<tfoot style="display:table-footer-group; font-weight:bold">
<tr>
<td colspan="2" align="center" style="font-weight:bold; border:3px double blue"> 每頁都有的表尾 </td>
</tr>
</tfoot>
</table>
<div align="center">
<input type="button" value="列印" onclick="javascript:window.print()" />
</div>
</body>
</html>
瀏覽器對表格元素的 page-break-after 支援度不一。最佳做法是將資料拆分為多個獨立的 <div class="page"> 容器,每個容器包含一個完整的表格(含表頭、表尾),並透過列印專用樣式控制分頁。
@media print {
div.page {
page-break-after: always;
page-break-inside: avoid;
}
.hide { display: table-header-group !important; }
}
@media screen {
.hide { display: none; }
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>分頁列印範例</title>
<style type="text/css" media="print">
div.page { page-break-after: always; page-break-inside: avoid; }
.hide { display: table-header-group !important; }
</style>
<style type="text/css">
.hide { display: none; }
</style>
</head>
<body>
<div class="page">
<table border="0" style="font-size:9pt;" width="300px" align="center">
<thead style="display:table-header-group; font-weight:bold">
<tr><td colspan="2" align="center" style="font-weight:bold; border:3px double red">每頁都有的表頭</td></tr>
</thead>
<tbody>
<tr><td>表格內容</td><td>表格內容</td></tr>
...
<tr><td>在這個之後分頁</td><td>在這個之後分頁</td></tr>
</tbody>
<tfoot style="font-weight:bold" class="hide">
<tr><td colspan="2" align="center" style="font-weight:bold; border:3px double blue">每頁都有的表尾</td></tr>
</tfoot>
</table>
</div>
<div class="page">
<table border="0" style="font-size:9pt;" width="300px" align="center">
<thead style="font-weight:bold" class="hide">
<tr><td colspan="2" align="center" style="font-weight:bold; border:3px double red">每頁都有的表頭</td></tr>
</thead>
<tbody>
<tr><td>表格內容</td><td>表格內容</td></tr>
...
</tbody>
<tfoot style="display:table-footer-group; font-weight:bold">
<tr><td colspan="2" align="center" style="font-weight:bold; border:3px double blue">每頁都有的表尾</td></tr>
</tfoot>
</table>
<div align="center"><input type="button" value="列印" onclick="window.print()" /></div>
</div>
</body>
</html>
div.page,每個獨立分頁。@media print 隱藏/顯示表頭表尾,確保每頁都有完整的表頭與表尾。<tr>、<tbody> 等表格內部元素套用分頁樣式。參考資源:StackOverflow 討論