1 回答

TA貢獻2019條經驗 獲得超9個贊
問題
這很可能是因為您已將抽屜和導航欄(左側導航和頂部導航)的可見性設置為隱藏。當某些內容的可見性設置為 時hidden
,它仍然在布局中并保留其高度、寬度、邊距和填充。這就是為什么您會看到抽屜和導航欄的空間,分別導致左側和頂部的空間。
您可以運行并嘗試打印以下屏幕。你會看到我提到的問題(由保留的尺寸[高度、寬度、填充、邊距]引起的空間)。
@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>
解決方案
我的建議是為可打印區域設置一個特殊的 id 或類。body
然后,將內部沒有此類特殊 id 或類的所有其他元素的可見性設置為隱藏。此外,由于將可見性設置為隱藏仍然允許元素保留其尺寸,因此也將其尺寸(高度、寬度、邊距和填充)設置為 0。請注意,您無法使用display: none
,因為您的可打印區域也不會顯示。
這是一個可以解決您的問題的工作示例。
@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 關注
- 238 瀏覽
添加回答
舉報