In web development, you may encounter scenarios where you need to control the visibility of specific content based on whether the user is printing a page. CSS provides a solution to this through its "@media print" feature.
Browser Support
Most major browsers support "@media print," ensuring that your print styles will work on modern devices.
Hiding Non-Printable Elements
To display only selected elements when printing, we can approach it in two ways:
Direct Tagging Method:
@media print { * { display: none; } .printable, .printable > * { display: block; } }
Negative Selection Method:
@media print { body *:not(.printable *) { display: none; } }
Handling Links and Logos
In addition to hiding non-printable elements, you may also want to display logos or letterhead information only on printed pages. This can be achieved using the following approach:
@media print { .noPrint { display:none; } } @media screen { .onlyPrint { display: none; } }
<div class="noPrint"> <a href="links.html">Links</a> </div> <div class="onlyPrint"> <img src="logo.png"> <img src="letterhead.png"> </div>
This will hide elements with the "noPrint" class in print mode, while displaying elements with the "onlyPrint" class only on printed pages.
The above is the detailed content of How to Control Content Visibility for Printing in CSS?. For more information, please follow other related articles on the PHP Chinese website!