How can I use CSS to control which elements are displayed when printing a web page?

Mary-Kate Olsen
Release: 2024-11-12 11:33:02
Original
260 people have browsed it

How can I use CSS to control which elements are displayed when printing a web page?

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:

  • Chrome
  • Firefox
  • Safari
  • Edge

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;
    }
}
Copy after login

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;
    }
}
Copy after login

This technique would hide everything except elements with the "printable" class when printing.

Additional Considerations

  • To avoid showing linked content when printing, add the "noPrint" class to the appropriate elements or links.
  • For displaying logos, letterhead, or other elements that should only appear when printing, create sections with the "onlyPrint" class.
CSS:
@media print {
    .noPrint {
        display: none;
    }
}
@media screen {
    .onlyPrint {
        display: none;
    }
}
Copy after login
HTML:
<div class="noPrint">
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template