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

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

html - @Media print css

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

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

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...