Explain Codes LogoExplain Codes Logo

Print `` only?

html
responsive-design
css
javascript
Anton ShumikhinbyAnton Shumikhin·Sep 7, 2024
TLDR

Want to print only the content within <div id="printarea"></div>? You can implement this with a CSS media query designed for printing. Then, use a JavaScript event triggered by a button click for triggering the print function.

Below is a compact example:

<style> @media print { body * { visibility: hidden; // Hide all elements (they're playing hide and seek) } #printarea, #printarea * { visibility: visible; // But #printarea needs to stay, it's the seeker! } #printarea { position: absolute; // Move #printarea to the top left corner (Not shy at all!) left: 0; top: 0; } } </style> <button onclick="window.print()">Print Content</button> <div id="printarea">Add printable content right here!</div>

OnClick, that neat button activates your browser's print operation, displaying only the content situated in #printarea.

Customizing for various scenarios

Getting print layout right

For achieving a spotless layout, make adjustments, and test in different browsers to ensure uniformity. Move #printarea to the front stage and set non-printable elements invisible or offscreen.

Master the art of content change

While CSS manages visibility, employ JavaScript to handle dynamic content. The innerHTML property grants you access into #printarea text for modification prior to printing.

Restore the original glory

Plan to return the original page layout to view after you're done with printing. This involves undoing any JavaScript modifications you have performed.

Keep it light and clean

Avoid relying heavily on heavyweight libraries like jQuery, especially for tasks that Vanilla JS can handle with equal finesse. Remember, less is more!

Go the extra mile to ace print media

Responsive printing is key

Adapt the styles within @media print to best fit various paper sizes and orientations. This ensures an optimal layout for every print media type.

Choose colors and fonts wisely

Printer-friendly? Yes, please! High-contrast colors and legible fonts render well on print. And remember, most printers are black/white — design for grayscale.

Too busy? Minimize print-specific classes

Instead of tagging every other element with .noprint, apply broader @media print rules. That's right, directly target the children of #printarea in your CSS to clearly separate web and print styles.

Ditch popup blockers

Opening new windows for print can trigger browser popup blockers. Inline methods that use the existing window are much smoother.

References