Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have my HTML page with this structure:

<html>
<head></head>
<body>
<nav>
  ....  navigation menu
</nav>
   <div>
         <div></div>
         <div class="to-print">
           <h2>My div to display in print mode<h2>
           <section>
               <article>....content....</article>
           </section>
         </div>
         <div></div>
   </div>
   <div>
      .... HTML elements
   </div>
</body>
</html>

If a user tries to print the page, I want only the content of the DIV with class to-print to be printed. How can I achieve that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
618 views
Welcome To Ask or Share your Answers For Others

1 Answer

If that is the exact structure of your html then this will work for you.

@media print {
  nav, 
  div > div:not(.to-print), 
  div + div:not(.to-print) {
      display: none;
  }
}

/* So you can see the styles working on the elements you want to hide outside of print */
  nav, 
  div > div:not(.to-print), 
  div + div:not(.to-print) {
      color: red;
  }
<nav>
  ....  navigation menu
</nav>
   <div>
         <div></div>
         <div class="to-print">
           <h2>My div to display in print mode<h2>
           <section>
               <article>....content....</article>
           </section>
         </div>
         <div></div>
   </div>
   <div>
      .... HTML elements
   </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...