Home > Web Front-end > CSS Tutorial > How to Print Only Selected HTML Content on Button Click?

How to Print Only Selected HTML Content on Button Click?

Barbara Streisand
Release: 2024-10-27 03:13:29
Original
829 people have browsed it

How to Print Only Selected HTML Content on Button Click?

Printing HTML Content Selectively on Button Click

Web developers often encounter the need to allow users to print specific sections of a web page without including the entire page content. In this context, the question arises:

How can we print only selected HTML content when a button is clicked, excluding the rest of the page?

Solution:

The suggested solution to keep the hidden HTML content in a display: print div is a valid approach. However, there is a simpler and more efficient method:

Create a Print Stylesheet:

  1. Create a CSS file named "print.css" containing the following code:
<code class="css">@media print {
  .noPrint {
    display: none;
  }
}</code>
Copy after login

This code will hide elements with the class "noPrint" when the page is printed.

  1. Apply the NoPrint Class:

Identify the HTML content that should not be printed and add the class "noPrint" to these elements, such as:

<code class="html"><h1 class="noPrint">No Print</h1></code>
Copy after login
  1. Include the Print Stylesheet:

Add the following line to the section of your HTML document:

<code class="html"><link rel="stylesheet" href="print.css" media="print"></code>
Copy after login
  1. Add the Print Button:

Create a button that triggers the print dialog when clicked:

<code class="html"><button onclick="window.print()">Print</button></code>
Copy after login

Explanation:

When the print button is clicked, the window.print() method is called, opening the browser's print dialog. The CSS media query @media print { ... } is triggered, causing the elements with the class "noPrint" to be hidden. As a result, only the desired HTML content is printed.

The above is the detailed content of How to Print Only Selected HTML Content on Button Click?. 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