@Media print css

心已入冬 提交于 2019-12-01 21:55:55

问题


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?


回答1:


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>



回答2:


You can you @media print and @media screen to define what will be printed and what will be shown on screen.

 @media print {
       .to-print {
           --css to show content--
       }
 }

 @media screen {
       .to-print {
           --css to not show content--
       }
 }

or

Create a new css and include like this:

  <link rel="stylesheet" type="text/css" href="/print.css" media="print">


来源:https://stackoverflow.com/questions/32699436/media-print-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!