【问题标题】:Use CSS to hide contents on print使用 CSS 隐藏打印内容
【发布时间】:2011-06-16 13:26:27
【问题描述】:

我正在寻找一种简单的方法来隐藏除特定 div 及其内容之外的所有内容。

<html>
  <head></head>
  <body>
    <div class="header">...</div>
    <div class="menu">...</div>
    <div class="content">...</div>
    <div class="footer">...</div>
  </body>.
</html>

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

.header, .menu, .footer {
  display: none;
}

如果布局复杂,就会变得凌乱。有没有更简单的方法来使用 CSS 做到这一点?

【问题讨论】:

标签: css printing


【解决方案1】:

我是用 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;
}

这样,即使在非常复杂的布局中,您也可以消除除要打印的内容之外的所有内容。 :not 在这里非常有效,因为它会处理您将来对 html 的任何修改。

【讨论】:

    【解决方案2】:

    根据您的 HTML 结构(以及您需要支持的浏览器,因为 IE6 不支持此功能),您可以隐藏所有顶级 div 并只显示您想要显示的一个/几个:

    body > div {
       display: none;
    }
    
    #content {
      display: block;
    }
    

    【讨论】:

      【解决方案3】:

      你可以使用类。

      .classHide{display: none}
      

      根据您使用的语言,当 if==true 时,您可以将类添加到页眉、菜单和页脚。

      所以你不需要使用另一个 css 文件。

      【讨论】:

      • 你如何告诉这些只在使用 CSS 以外的任何东西打印时隐藏?
      • 我的意思是,您不能使用服务器端语言来告诉样式仅在打印时应用。这是因为打印发生在客户端,所以服务器什么都不知道。
      【解决方案4】:

      分配一个单独的 CSS 文件来定义打印网页时的行为。

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

      然后在该文件中定义:

      .header, .menu, .footer { display: none; }
      

      【讨论】:

        【解决方案5】:
        @media print {
        .noPrint {
            display:none;
          }
        }
        

        现在您需要将noPrint 类应用到要在打印中隐藏的元素。


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

        示例:

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

        【讨论】:

        • 确保在指定所有其他样式部分之后添加打印部分。这样打印语句将在打印时覆盖其他样式。
        • 问题说:looking for an easy way to hide everything except a certain div
        • 这应该是公认的答案。它是所有其他答案中最灵活的,不涉及使用 JS 或使用某些 JS 插件手动显示隐藏元素。
        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2019-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        相关资源
        最近更新 更多