简体   繁体   中英

Print part of the web page with CSS

I am working on a page, where the user may click a button and print some important information on the page.

Basic page structure is like:

<body>

    <div id="printContent"></div>

    <button>Print</button>

</body>

And the desired behavior is: when the page is being printed, only the contents inside "printContent" should be printed.

Before I used js code to do it by temporarily replacing the body with whatever is inside printContent, but this seems to slow down the page a bit when user gets out of the printing options pop-up. (The temporary content will occupy the whole page for a few seconds or some of the buttons and links become non-responsive for a few seconds.) So after referring to the second answer here: How do I print part of a rendered HTML page in JavaScript?

I used something like this:

@media print {
  body * {
    display:none;
  }

  body #printContent {
    display:block;
  }
}

But when printing, the printContent part is still invisible. Did I do anything wrong here? Thanks.

EDIT: My bad, it is not the second answer from the link, the second "Highest upvoted answer", namely the one with 15 upvotes.

Okay, might be a lot of sub elements getting affected too. Try this:

@media print {
  body * {
    display:none;
  }

  body #printContent {
    display:block;
  }

  body #printContent * {
    display:initial;
  }
}

Technically, you are resetting the display for the inner contents too. Do you understand? When you give the global selector body * , it also hides the inner components. So just unhiding the parent #printContent will not be sufficient to unhide the children of it. To avoid all these hassles, you can do something like this if the #printContent is a direct descendant of body :

@media print {
  body > * {
    display:none;
  }

  body > #printContent {
    display:block;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM