使用CSS隐藏打印内容

Dzi*_*mid 10 css printing

我正在寻找一种简单的方法来隐藏除了某个div及其内容之外的所有内容.

<html>
  <head></head>
  <body>
    <div class="header">...</div>
    <div class="menu">...</div>
    <div class="content">...</div>
    <div class="footer">...</div>
  </body>.
</html>
Run Code Online (Sandbox Code Playgroud)

所以,例如,如果我只想打印div.content,我会这样做:

.header, .menu, .footer {
  display: none;
}
Run Code Online (Sandbox Code Playgroud)

如果布局复杂,它就会变得混乱.使用CSS有更简单的方法吗?

Sar*_*raz 28

@media print {
.noPrint {
    display:none;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,您需要将类noPrint应用于要在打印中隐藏的元素.


最好使用专门用于打印的样式表,并将其设置为media属性print.

例:

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

  • 这应该是公认的答案。它是所有其他答案中最灵活的,并且不涉及使用 JS 或使用某些 JS 插件来手动显示-隐藏元素。 (2认同)

Dzi*_*mid 7

我做了css3方式:使用非伪类和直接祖先(儿童)

/* hide all children of body that are not #container */
body > *:not(#container) {
  display: none;
}
/* hide all children of #container that are not #content */
#container > *:not(#content) {
  display: none;
}
/* and so on, until you reach a div that you want to print */
#content > *:not(#print_me) {
  display: none;
}
Run Code Online (Sandbox Code Playgroud)

这样,即使在非常复杂的布局中,您也可以消除除了要打印的内容之外的所有内容.:这里效率不高,因为它会照顾你未来对你的HTML的修改.


Tr1*_*tan 6

分配一个单独的CSS文件,用于定义打印网页时的行为.

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

然后在该文件中定义:

.header, .menu, .footer { display: none; }
Run Code Online (Sandbox Code Playgroud)