網頁列印樣式控制是前端常見需求。本文系統整理 CSS 列印媒體查詢、jQuery 動態控制、常見坑點與最佳實務。
<!-- 螢幕顯示樣式 -->
<link rel="stylesheet" href="css/screen.css" media="screen">
<!-- 列印專用樣式 -->
<link rel="stylesheet" href="css/print.css" media="print">
<style>
@import url("css/screen.css") screen;
@import url("css/print.css") print;
</style>
<style>
/* 螢幕共用樣式 */
.header { color: #333; }
.btn { display: inline-block; padding: 8px 16px; }
/* 列印專用樣式 */
@media print {
.header { color: #000 !important; }
.btn, .nav, .sidebar, .footer, .ads { display: none !important; }
.content { width: 100%; max-width: none; margin: 0; padding: 0; }
a[href^="http"]::after { content: " (" attr(href) ")"; font-size: 0.9em; color: #666; }
.page-break { page-break-before: always; }
.no-break { page-break-inside: avoid; }
}
</style>
@media print {
.no-print, .nav, .sidebar, .footer, .ads, .btn, .modal { display: none !important; }
}
@media print {
* {
background: transparent !important;
color: #000 !important;
box-shadow: none !important;
text-shadow: none !important;
}
/* 強制白背景 */
body { background: white !important; }
}
@media print {
body { font-size: 12pt; line-height: 1.5; }
h1 { font-size: 18pt; }
.container { width: 18cm; margin: 0 auto; } /* A4 寬度約 19cm 扣除邊距 */
}
@media print {
.col, .float-left, .float-right { float: none !important; width: 100% !important; }
.clearfix::after { display: block; content: ''; clear: both; }
}
@media print {
/* 強制分頁:章節標題前分頁 */
h1, h2.chapter { page-break-before: always; }
/* 避免表格/圖片被截斷 */
table, img, .chart, .card { page-break-inside: avoid; }
/* 區塊結束後分頁 */
.section-end { page-break-after: always; }
/* 左右頁邊距(雙面列印) */
@page { margin: 2cm 1.5cm; }
@page :left { margin-right: 2cm; }
@page :right { margin-left: 2cm; }
}
@media print {
/* 僅顯示外部連結 URL */
a[href^="http"]::after {
content: " (" attr(href) ")";
font-size: 0.85em;
color: #666;
word-break: break-all;
}
/* 內部連結不顯示 */
a[href^="/"]::after,
a[href^="#"]::after {
content: "";
}
}
$('#printBtn').on('click', function() {
window.print();
});
function enablePrintStylesheet() {
// 移除現有 print 樣式表
$('link[media="print"]').remove();
// 新增動態產生的列印樣式
const printCss = `
@media print {
.no-print { display: none !important; }
.content { width: 100% !important; }
}
`;
$('head').append(``);
}
// 列印前準備
$('#printBtn').on('click', function() {
enablePrintStylesheet();
// 可選:展開所有摺疊內容
$('.collapsible').addClass('expanded');
window.print();
});
function printArea(selector) {
const content = $(selector).html();
const iframe = $('
| 現象 | 原因 | 解決 |
|---|---|---|
| 背景色/圖不列印 | 瀏覽器預設不列印背景 | 使用者需在列印對話框勾選「背景圖形」;或用 border 替代 |
| 浮動元素內容被截斷 | Gecko 核心截斷浮動內容 | @media print { float: none; } |
| 字體過大/過小 | px 單位不適合列印 | 使用 pt、cm、mm、in |
| 頁首頁尾重複 | 瀏覽器自動加入 URL、日期、頁碼 | @page { margin: 0; } 或列印設定關閉 |
| iframe 內容不列印 | 父頁面列印不包含 iframe | 在 iframe 內呼叫 print() 或用 iframe 法 |
print.css,使用 media="print" 載入.no-print 工具類別,標記不需列印元素!important 覆蓋螢幕樣式pt/cm,避免 pxpage-break-inside: avoid