Displaying Selective Content When Printing with CSS
Many web pages contain extensive data, layouts, and content. To optimize printing, you may want to display only specific elements. While creating a separate page for printing can be a solution, CSS provides a powerful alternative with its "@media print" feature.
Browser Support for "@media print"
The "@media print" feature is widely supported by modern browsers. It allows you to apply CSS rules specifically when the page is being printed. Browsers that support "@media print" include:
Targeting Elements for Printing
To hide all elements except those you wish to print, you can use the "display:none" property. Then, add a "printable" class to elements you want to display when printing and apply "display:block" to these elements within the "@media print" block.
CSS:
@media print { * { display: none; } .printable, .printable > * { display: block; } }
However, if you wish to display elements only when printing and hide them in the browser, consider using an inverse approach:
CSS:
@media print { body *:not(.printable *) { display: none; } }
This technique would hide everything except elements with the "printable" class when printing.
Additional Considerations
CSS:
@media print { .noPrint { display: none; } } @media screen { .onlyPrint { display: none; } }
HTML:
<div class="noPrint">
By following these methods, you can easily control the visibility of specific elements when printing web pages, reducing clutter and optimizing printing efficiency.
The above is the detailed content of How can I use CSS to control which elements are displayed when printing a web page?. For more information, please follow other related articles on the PHP Chinese website!