@Media print css

ttcibm8c  于 2023-04-13  发布在  其他
关注(0)|答案(3)|浏览(141)

我的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>

如果用户尝试打印页面,我希望只打印类为to-print的DIV的内容。如何实现这一点?

gwo2fgha

gwo2fgha1#

如果这是你的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;
  }
<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>
gywdnpxw

gywdnpxw2#

您可以使用**@media print@media screen**来定义要打印的内容和屏幕上显示的内容。

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

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


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

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

w80xi6nr3#

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

/* 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: blue;
  }
<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>

看到这是不工作,请纠正,如果有任何事情错了。默认颜色,我有蓝色,当我打印的页面,导航栏应该我红色

相关问题