How to set div height to 100% of chosen print pape

2020-08-09 10:59发布

问题:

How can i set the height to 100% of chosen print paper?

CSS

width: 100%;
height: 100%;
margin: auto;
margin-top: 0px !important;
border: 1px solid;

When i print in Google Chrome, my printed div will only be as high as the content in the div.
Can i solve this?
Is it possible to make a div as high as chosen paper size?

回答1:

width: 100%;
height:100%;
position:absolute;
top:0px;
bottom:0px;
margin: auto;
margin-top: 0px !important;
border: 1px solid;

also, if position absolute won't work you can do the same with position:fixed; this will work but might do some more damage to your layout, depending on how everything is arranged :)

I'll edit this to make it more obvious, so... if you are using position fixed and you have multiple pages they will just go one on top of the other so that wouldn't be right... but in order to get the right result with position absolute you have to keep in mind that the css style here will take 100% of the height, but it's the height of it's parent... so if the parent is the body just add html, body{ height:100% };



回答2:

Have a look at media queries.

@media print {
    html, body {
        height: 100%;
    }
}

So you can change output without messing up your screen layout



回答3:

The easiest way I found to do this was use Viewport units and page-break-after:always. This works well for printing multiple pages.

I suggest structuring your HTML like this:

<div class="someContainerClass">
  <section id="pageOne"></section>
  <section id="pageTwo"></section>
  <section id="pageThree"></section>
</div>

And using this CSS:

section {
  width: 100vw;
  height: 100vh;
  page-break-after: always;
}

This way you can contain your content in the page it needs to be.



回答4:

If you add a page break to the end, the element will extend to the bottom of the last page. It's particularly useful if you want a footer to appear at the bottom of the last page:

<div style='position:relative;overflow:hidden;background:#ffe!important'>
    <div style='margin-bottom:200px'>
        <p>Content here</p>
    </div>
    <div style='page-break-before:always'></div>
    <div style='position:absolute;bottom:0'>Footer</div>
</div>

This won't give you an extra blank page - so long as you don't have any content after the page break (the absolutely positioned footer doesn't count, unless it somehow spills onto the second page). Watch out for margins which extend outside the body!



回答5:

You need to make your body 100% this should work.

html, body {
    height: 100%;
}

This needs to be done because as you know your content is within the body. The body does not have a default height of 100%, so the bodys height will just adapt to the content within itself, unless you manually give it a height like shown in the example above.



标签: css printing