css - 如何只打印页面的特定部分?

标签 css

我知道,为了防止打印某些页面部分,我们可以添加一个类并告诉 CSS 我们不希望打印该类中的元素。 例如:

页面.html:

<div class="main">
<div class = "section1 donotprint">
  <p>Hey, I'm not printed. Poor me.</p>
</div>
<div class = "section2">
  <p>Hey, I am printed! Lucky me!</p>
</div>

打印.css:

.donotprint {
  display: none;
}

然后包括<link rel="stylesheet" type="text/css" media="print" href="print.css" />发挥魔力。

但是我正在处理一个相当繁重的元素,我不想到处都有 donotprint 类污染代码。所以我想指定我想要打印的内容,而不是指定我不想打印的内容。所以在我的例子中它会是这样的:

页面.html:

<div class="main">
<div class = "section1">
  <p>Hey, I'm not printed. Poor me.</p>
</div>
<div class = "section2 print">
  <p>Hey, I am printed! Lucky me!</p>
</div>

我试过:not(.print) {display: none;}但是display: none;也会影响 children ,因此不会打印任何内容(嗯,空的 <div class = "section2 print"></div> 是)。

那么 CSS 允许这种事情吗?如果是这样,怎么办?

最佳答案

您可以将*选择器与直接子>结合使用

.main > * {       /* Basically the sections */
  display: none; 
}

.main > .print {
  display: initial;
}

上面的内容不像专门定义要隐藏的内容那样灵活 - 因为它仅适用于直系子代。

关于css - 如何只打印页面的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52537980/

相关文章:

html - 双点 CSS 选择器?

css - Bootstrap 4 navbar flex 之间?

html 按钮,值 ="submit"没有显示?

javascript - 页面滚动时的div位置

javascript - 使用 JSBarcode 库无法正确打印条码

javascript - 如何使用 jQuery 或 Javascript 沿对 Angular 线滚动

php - Bootstrap 3 站点 : migrate to Wordpress or Password set up

php - Bootstrap 3 Navbar 不会在移动设备上折叠

javascript - 对齐d3折线图中的标签

javascript - 使用 jQuery 错误编译 coffeescript