1 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
問題
這很可能是因?yàn)槟褜⒊閷虾蛯?dǎo)航欄(左側(cè)導(dǎo)航和頂部導(dǎo)航)的可見性設(shè)置為隱藏。當(dāng)某些內(nèi)容的可見性設(shè)置為 時(shí)hidden
,它仍然在布局中并保留其高度、寬度、邊距和填充。這就是為什么您會看到抽屜和導(dǎo)航欄的空間,分別導(dǎo)致左側(cè)和頂部的空間。
您可以運(yùn)行并嘗試打印以下屏幕。你會看到我提到的問題(由保留的尺寸[高度、寬度、填充、邊距]引起的空間)。
@media print {
body,
html,
#wrapper {
width: 100%;
margin: 0px;
padding: 0px;
border: 1px solid red;
}
#drawer {
visibility: hidden;
}
#navbar {
visibility: hidden;
}
.no-print {
display: none;
}
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html,
body {
position: relative;
width: 100%;
height: 100%;
}
#wrapper {
display: flex;
flex-direction: row;
height: 100%;
width: 100%;
}
#navbar {
width: 100%;
background: blue;
color: white;
padding: 20px;
}
#section--right {
flex-grow: 1;
}
#drawer {
height: 100%;
width: 100px;
background: red;
color: white;
padding: 20px;
}
#navbar .text {
display: inline-block;
height: 50px;
background: #121212;
}
<div id="wrapper">
<div id="drawer">Some drawer</div>
<div id="section--right">
<div id="navbar"><span class="text">Some navbar</span></div>
<div id="print__section">
test
</div>
<button id="print__button" class="no-print" onclick="window.print()">Print now</button>
</div>
</div>
解決方案
我的建議是為可打印區(qū)域設(shè)置一個(gè)特殊的 id 或類。body
然后,將內(nèi)部沒有此類特殊 id 或類的所有其他元素的可見性設(shè)置為隱藏。此外,由于將可見性設(shè)置為隱藏仍然允許元素保留其尺寸,因此也將其尺寸(高度、寬度、邊距和填充)設(shè)置為 0。請注意,您無法使用display: none
,因?yàn)槟目纱蛴^(qū)域也不會顯示。
這是一個(gè)可以解決您的問題的工作示例。
@media print {
body,
html,
#wrapper {
width: 100%;
margin: 0px;
padding: 0px;
border: 1px solid red;
}
/* Makes all divs that are not inside the print region invisible */
/* Then, set the size to 0 by setting everything (height, width, margin, and padding) to 0 */
body *:not(#print__section) {
visibility: hidden;
height: 0;
width: 0;
margin: 0;
padding: 0;
}
/* Parents' visibility cascade to children's visibility */
/* Make the print region visible again to override parent's visibility */
#print__section {
visibility: visible;
}
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html,
body {
position: relative;
width: 100%;
height: 100%;
}
#wrapper {
display: flex;
flex-direction: row;
height: 100%;
width: 100%;
}
#navbar {
width: 100%;
background: blue;
color: white;
padding: 20px;
}
#section--right {
flex-grow: 1;
}
#drawer {
height: 100%;
width: 100px;
background: red;
color: white;
padding: 20px;
}
#navbar .text {
display: inline-block;
height: 50px;
background: #121212;
}
<div id="wrapper">
<div id="drawer">Some drawer</div>
<div id="section--right">
<div id="navbar"><span class="text">Some navbar</span></div>
<div id="print__section">
test
</div>
<button id="print__button" class="no-print" onclick="window.print()">Print now</button>
</div>
</div>
- 1 回答
- 0 關(guān)注
- 235 瀏覽
添加回答
舉報(bào)