Home > Web Front-end > CSS Tutorial > How to Control Content Visibility for Printing in CSS?

How to Control Content Visibility for Printing in CSS?

Barbara Streisand
Release: 2024-11-21 02:21:15
Original
930 people have browsed it

How to Control Content Visibility for Printing in CSS?

Printing-Specific CSS: Displaying Selected Content

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:

  1. Add a "printable" class to the elements you want to print.
  2. Use "@media print" to hide all elements except those with the "printable" class:
@media print {
  * { display: none; }
  .printable, .printable > * { display: block; }
}
Copy after login

Negative Selection Method:

  1. Instead of tagging printable elements, we can hide all non-printable elements:
@media print {
  body *:not(.printable *) { display: none; }
}
Copy after login

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;
   }
}
Copy after login
<div class="noPrint">
   <a href="links.html">Links</a>
</div>
<div class="onlyPrint">
   <img src="logo.png">
   <img src="letterhead.png">
</div>
Copy after login

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!

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