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

How Can I Print Only a Specific Div Using CSS Media Queries?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 08:12:23470browse

How Can I Print Only a Specific Div Using CSS Media Queries?

Printing Specific Content Using CSS Media Queries

The request to print solely a specific div on a web page presents a challenge when trying to preserve its appearance and exclude unwanted elements. This issue can be addressed effectively using CSS media queries.

The following CSS code snippet offers a solution that allows you to print the specified div without affecting other content on the page:

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

In this CSS code:

  • The @media print {} block defines print-specific styles.
  • The body element is assigned visibility: hidden to conceal all other elements on the page.
  • The #section-to-print div (which contains the desired content) is assigned visibility: visible to ensure its appearance in print.
  • position: absolute along with left: 0 and top: 0 ensure that the div is positioned correctly in the printable area.

By utilizing this method, you can print the desired div without triggering a new print preview dialog or altering the original page layout.

The above is the detailed content of How Can I Print Only a Specific Div Using CSS Media Queries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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