使用 CSS 隐藏打印内容 [英] Use CSS to hide contents on print
问题描述
我正在寻找一种简单的方法来隐藏除某个 div 及其内容之外的所有内容.
I’m looking for an easy way to hide everything except a certain div and its contents.
<html>
<head></head>
<body>
<div class="header">...</div>
<div class="menu">...</div>
<div class="content">...</div>
<div class="footer">...</div>
</body>.
</html>
例如,如果我只想打印 div.content
,我会这样做:
So, for example, if I want to print only div.content
, I would do it like this:
.header, .menu, .footer {
display: none;
}
如果布局复杂,就会变得凌乱.有没有更简单的方法可以用 CSS 做到这一点?
And if the layout is complicated, it becomes messy. Is there an easier way to do this with CSS?
推荐答案
我是用 css3 的方式做到的:不使用伪类和直接祖先(孩子)
I did it css3 way: using not pseudo class and direct ancestors (children)
/* 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 的任何修改.
This way you can eliminate everything except what you want to print even in very complex layouts. :not is very efficient here because it takes care about any future modifications of you html.
这篇关于使用 CSS 隐藏打印内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!