@Media 打印 css

Ker*_*Med 5 html css media printing

我的 HTML 页面具有以下结构:

<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>
Run Code Online (Sandbox Code Playgroud)

如果用户尝试打印页面,我只想打印带有类的 DIV 的内容to-print。我怎样才能做到这一点?

Aar*_*ron 5

如果那是您的 html 的确切结构,那么这对您有用。

@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;
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


小智 4

您可以@media print@media screen来定义将打印的内容以及将在屏幕上显示的内容。

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

 @media screen {
       .to-print {
           --css to not show content--
       }
 }
Run Code Online (Sandbox Code Playgroud)

或者

创建一个新的 css 并包含如下内容:

  <link rel="stylesheet" type="text/css" href="/print.css" media="print">
Run Code Online (Sandbox Code Playgroud)