ภาพรวม
ใช้ CSS Media Query @media print เพื่อกำหนด Style ที่มีผลเฉพาะตอนพิมพ์ (Print) เท่านั้น
วิธีที่ 1: ใช้ Class .noprint
/* CSS */
@media print {
.noprint {
display: none; /* หรือ visibility: hidden; */
}
}
HTML
<div class="noprint">
เนื้อหานี้จะไม่แสดงตอนพิมพ์
<button>ปุ่มที่ไม่ต้องการพิมพ์</button>
</div>
<div>
เนื้อหานี้จะแสดงตอนพิมพ์ตามปกติ
</div>
วิธีที่ 2: ใช้ ID Selector
@media print {
#header, #footer, #sidebar, .ad-banner, .no-print {
display: none;
}
}
วิธีที่ 3: ซ่อน Element เฉพาะ (Page Break Control เพิ่มเติม)
@media print {
.noprint { display: none; }
/* ป้องกันการตัดหน้าระหว่าง Element */
.no-break { page-break-inside: avoid; }
/* บังคับขึ้นหน้าใหม่ */
.page-break-before { page-break-before: always; }
.page-break-after { page-break-after: always; }
/* ปรับขนาด Font ให้พอดีกระดาษ */
body { font-size: 12pt; }
/* ซ่อน Navigation, Ads, Buttons */
nav, .btn, .advertisement, .social-share { display: none; }
}
display: none vs visibility: hidden
| Property | พื้นที่ | Layout Impact |
|---|---|---|
display: none | ไม่ครอบครองพื้นที่ | Element อื่นจะเลื่อนมาเติม |
visibility: hidden | ครอบครองพื้นที่ไว้ | เว้นที่ว่างไว้ |
แนะนำ: ใช้ display: none สำหรับการพิมพ์ เพื่อให้ Layout ติดกันสวยงาม
ตัวอย่างครบถ้วน
<!DOCTYPE html>
<html>
<head>
<style>
@media print {
.noprint, nav, .sidebar, .ads, button, .no-print {
display: none !important;
}
.content {
width: 100%;
margin: 0;
padding: 0;
}
body {
font-size: 12pt;
line-height: 1.5;
}
}
</style>
</head>
<body>
<nav class="noprint">Navigation Menu</nav>
<div class="content">
<h1>Article Title</h1>
<p>Main content...</p>
</div>
<aside class="sidebar noprint">Sidebar</aside>
<button class="noprint">Print</button>
</body>
</html>