Home >Web Front-end >JS Tutorial >How to Print Only a Specific HTML Element Using CSS?
How to Print a Specific HTML Element Only
The task of printing solely a specific HTML element, such as a div, often arises in web development. However, achieving this without disabling the visibility of other page content can be challenging.
To address this issue, there exists a CSS solution that allows you to print the desired element while concealing the rest of the page. By implementing the following code, you can specify that the entire page becomes invisible during printing, except for the div you wish to print:
@media print { body { visibility: hidden; } #section-to-print { visibility: visible; position: absolute; left: 0; top: 0; } }
In this code, the div you want to print is assigned the ID "section-to-print." When the browser enters print mode (which is triggered by the user's print command), the @media rule specified becomes active.
This rule sets the visibility property of the body tag to "hidden," rendering all page elements invisible. However, the visibility of the div with the ID "section-to-print" is explicitly set to "visible."
Additionally, to ensure proper printing, the div is positioned absolutely and placed at the top left corner of the page. This ensures that it appears in the desired location during printing.
Using this method, you can selectively print a specific div without the need for additional dialogs or manipulating the page's structure. It offers a clean and effective solution for situations where printing a specific HTML element is required.
The above is the detailed content of How to Print Only a Specific HTML Element Using CSS?. For more information, please follow other related articles on the PHP Chinese website!