π What Is @media print?
The @media print rule allows you to define styles that applyonly when the webpage is printed or previewed in print mode. This is essential for creating clean, print-friendly documents such as invoices, resumes, tickets, reports, certificates, and more. πβ¨
π― Why Use @media print?
- Remove UI elements (buttons, navigation bars, ads)
- Force white backgrounds for readable printing
- Optimize layout for A4, Letter, receipts, etc.
- Format text differently for print (font size, spacing)
- Hide unnecessary animations, colors, or shadows
π§© Basic Syntax
Basic @media print Rule
@media print {
/* Print-only CSS here */
body {
font-size: 12pt;
}
}Anything inside @media print applies ONLY during printing or print preview.
π¨οΈ Hiding Elements in Print
Hide Elements
@media print {
.no-print {
display: none !important;
}
}β Useful for buttons, banners, ads, navigation bars, or videos.
π¨ Formatting Text for Print
Adjust Print Typography
@media print {
h1 {
font-size: 20pt;
}
p {
line-height: 1.4;
font-size: 11pt;
}
}Print requires different text sizes and spacing for better legibility.
π Ensuring White Backgrounds
Some browsers don't print background colors/images unless explicitly enabled by the user. But you can still enforce layout clarity:
Force White Background
@media print {
body {
background: #fff !important;
color: #000 !important;
}
}Note
π Page Break Control
You can control how elements break across printed pages using:
- page-break-before
- page-break-after
- page-break-inside
Page Break Example
@media print {
h1 {
page-break-before: always;
}
table {
page-break-inside: avoid;
}
}π Combining @page + @media print
Structure for Print Documents
@media print {
@page {
size: A4;
margin: 15mm;
}
.no-print {
display: none !important;
}
h1 {
font-size: 24pt;
margin-bottom: 10mm;
}
}Using @page inside @media print gives full control: page size β margins β typography β visibility β layout.
π§ Advanced: Print-Only Layout Changes
Different Layout for Print
@media print {
.grid-layout {
display: block;
}
.sidebar,
.footer {
display: none;
}
.content {
width: 100%;
}
}β Converts grid layout into a single-column printable version
β Removes decorative UI elements
π Real Project Example: Invoice Print Styles
Invoice Print CSS
@media print {
@page { size: A4 portrait; margin: 12mm; }
body {
font-family: Arial, sans-serif;
}
header,
.sidebar,
.buttons,
.ads {
display: none !important;
}
.invoice-container {
padding: 0;
border: none;
width: 100%;
}
h2 {
font-size: 18pt;
}
}β Clean print output
β Removes UI clutter
β Applies precise page formatting
β Ensures fonts and spacing are print-friendly
π Best Practices
- Always test print styles on Chrome + Firefox
- Avoid heavy color backgrounds (printers may ignore them)
- Use pt and mm for precise sizing
- Keep print layout clean and minimalist
- Use !important when overriding framework styles