Home > Web Front-end > JS Tutorial > How Can I Print Only a Specific Div on a Web Page Using CSS?

How Can I Print Only a Specific Div on a Web Page Using CSS?

Patricia Arquette
Release: 2024-12-04 19:14:15
Original
214 people have browsed it

How Can I Print Only a Specific Div on a Web Page Using CSS?

Printing Specific Content on a Web Page

Printing only a specific div on a web page without affecting other content can be a challenging task. To address this, one effective approach utilizing CSS is presented below:

CSS Solution:

@media print {
  body {
    visibility: hidden;
  }
  #section-to-print {
    visibility: visible;
    position: absolute;
    left: 0;
    top: 0;
  }
}
Copy after login

Explanation:

This CSS code uses the @media print rule to apply styles specifically to the print preview. It works by:

  1. Hiding the entire body of the page (except for the div to be printed) by setting its visibility to hidden.
  2. Setting the visibility of the target div (#section-to-print) to visible.
  3. Positioning the target div absolutely at the top left of the page (left: 0; top: 0;) to ensure it prints correctly.

Alternative Approaches:

While using display to hide content may seem like an option, it can be challenging because any element hidden with display:none will also hide its descendants. This may require significant page restructuring.

Benefits of this Solution:

This CSS-only solution:

  • Allows you to selectively print only the desired div without disabling other page elements.
  • Avoids the creation of a new window, ensuring a seamless printing experience.
  • Preserves the visual styling of the target div for printing, even if the applied styles are meant for web display.

The above is the detailed content of How Can I Print Only a Specific Div on a Web Page Using 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